pandas 如何在pandas数据框中获得等效的numpy数组索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43839328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:33:17  来源:igfitidea点击:

How to get numpy arrays indexing equivalent in pandas data frame?

pythonarrayspandasnumpydataframe

提问by Liza

I have a numpy arrayas following:

我有一个 numpy数组,如下所示:

    array([[1, 2],
           [3, 4],
           [5, 6],
           [7, 8]])

The array is called myArray, and I perform two indexing operations on the 2D array and get following results:

该数组称为 myArray,我对二维数组执行两次索引操作并得到以下结果:

    In[1]: a1 = myArray[1:]
           a1

    Out[1]:array([[3, 4],
                 [5, 6],
                 [7, 8]])


    In[2]: a2 = myArray[:-1]
           a2

    Out[2]:array([[1, 2],
                  [3, 4],
                  [5, 6]])

Now, I have the same data in the form of a pandas df in two columns, let the data frame be df

现在,我在两列中以Pandas df 的形式拥有相同的数据,让数据框为 df

      x    y
   0  1    2
   1  3    4
   3  5    6
   4  7    8

How to do the equivalent indexing/ slicing on two columns to get the same results as above for a1 and a2.

如何对两列进行等效索引/切片以获得与上述 a1 和 a2 相同的结果。

采纳答案by Psidom

Use iloc:

使用iloc

df.iloc[1:]

#   x   y
#1  3   4
#3  5   6
#4  7   8

df.iloc[:-1]

#   x   y
#0  1   2
#1  3   4
#3  5   6

Use head/tail:

使用head/tail

df.head(-1)       # equivalent to df.iloc[:-1]

#   x   y
#0  1   2
#1  3   4
#3  5   6

df.tail(-1)       # equivalent to df.iloc[1:]

#   x   y
#1  3   4
#3  5   6
#4  7   8