【问题标题】:How to get numpy arrays indexing equivalent in pandas data frame?如何在熊猫数据框中获得等效的numpy数组索引?
【发布时间】:2017-10-05 23:09:41
【问题描述】:

我有一个 numpy array 如下:

    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]])

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

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

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

【问题讨论】:

  • 你可以使用df.values访问底层的numpy对象。

标签: python arrays pandas numpy dataframe


【解决方案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

【讨论】:

  • 如果df中有更多列,我只想在“x”和“y”列上得到结果。我知道我可以在索引后删除列,但是有没有办法只对选定的列执行索引?
  • df[['x', 'y']].iloc[1:] 怎么样?这是你要找的吗?
  • 非常感谢,这正是我想要的。
  • @Psidom 如何选择不跟随的多行?例如从 list=[1,10,25,100] 中选择行
猜你喜欢
  • 2017-09-11
  • 2018-06-18
  • 2020-05-24
  • 2022-07-10
  • 2021-09-18
  • 2018-05-12
  • 1970-01-01
  • 2018-03-01
  • 2021-01-19
相关资源
最近更新 更多