获取具有条件的pandas dataframe中指定索引

2024-03-29 10:43:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据帧:

id    value
14     122
15     120
16     190
17     490
18     328
19     309
20     323

我有一个id的列表L = [14,17,20],我想做两件事:

Get the list of indexes of those rows where for the id's is not in the list L

i.e.( index of rows 15,16,18,19)

而且

Delete the rows for the id's is not in the list L.

我的预期产出:

^{pr2}$

Tags: ofthe数据inid列表forget
2条回答

您可以将^{}^{}一起使用,以反转布尔掩码~

idx = df.index[~df['id'].isin(L)].tolist()
print (idx)
[1, 2, 4, 5]

然后^{}

^{pr2}$

备选方案:

df1 = df[df['id'].isin(L)]
print (df1)
   id  value
0  14    122
3  17    490
6  20    323

替代方案:

In [106]: df.query("id in @L")
Out[106]:
   id  value
0  14    122
3  17    490
6  20    323

相关问题 更多 >