2017-05-08 47 views
2

我有一个numpy的阵列如下:如何在熊猫数据框架中获得numpy数组索引相当于?

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

该数组名为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]]) 

现在,我在两列中有熊猫df形式的相同数据,让数据帧为df

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

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

+0

您可以使用'df.values'访问底层numpy的对象。 –

回答

1

使用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 

使用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 
+0

如果df中有更多列,那么该怎么办?我只想在“x”和“y”列上得到结果。我知道我可以在索引后删除这些列,但有没有办法只对选定的列进行索引? – Liza

+0

'df [['x','y']]。iloc [1:]'?这是你想要的? – Psidom

+0

非常感谢,这是我想要的。 – Liza

相关问题