【问题标题】:select multiple rows by index in pandas if it is in a list如果它在列表中,则在熊猫中按索引选择多行
【发布时间】:2020-01-01 14:23:25
【问题描述】:

类似于Select multiple sections of rows by index in pandas,我有很大的数据框,有一些我有兴趣查看的索引。

我有:

import pandas as pd 
df = pd.DataFrame({'A':[0,1,2,3,4,5,6,7,8,9],'B':['a','b','c','d','e','f','g','h','i','j']},
                  index=range(10,20,))

我想看的索引很少,list=[12,15,10,14]

所以我最终得到:

    A  B
12  2  c
15  5  f
10  0  a
14  4  e

有没有命令让我可以去:

df.iloc[[index isin list]]

因为值列表是由较早的一段代码组成的。

我试过了:

df.loc[[ix]]

ix=dm.iloc[250].sort_values()[:10].indexInt64Index([250, 1109, 427, 513, 678, 18, 697, 1075, 533, 739], dtype='int64')

无济于事。

欢迎提出建议!

【问题讨论】:

  • df.loc[list_] 也不要将变量命名为list,因为它是一个内置函数

标签: pandas indexing


【解决方案1】:

先把list改成另一个名字,比如L,因为python码字,然后按DataFrame.loc选择,按标签选择:

L=[12,15,10,14]
df = df.loc[L]
print (df)
    A  B
12  2  c
15  5  f
10  0  a
14  4  e

您的解决方案已接近使用DataFrame.iloc 函数的位置选择:

L1 = [2,5]
df = df.iloc[L1]

print (df)
    A  B
12  2  c
15  5  f

【讨论】:

    猜你喜欢
    • 2016-12-14
    • 1970-01-01
    • 2018-05-28
    • 2018-09-27
    • 1970-01-01
    • 2017-10-30
    • 2020-10-12
    • 2020-07-17
    • 2015-05-28
    相关资源
    最近更新 更多