gpt4 book ai didi

python - 获取列具有条件的 Pandas 数据框的指定索引

转载 作者:太空狗 更新时间:2023-10-30 02:39:46 26 4
gpt4 key购买 nike

我有一个 Pandas 数据框:

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.

我的预期输出:

id    value
14 122
17 490
20 323

最佳答案

您可以使用 boolean indexingisin , 用于反转 bool 掩码 ~:

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

然后 drop :

df1 = df.drop(idx)
print (df1)
id value
0 14 122
3 17 490
6 20 323

备选方案:

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

关于python - 获取列具有条件的 Pandas 数据框的指定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43472783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com