筛选pandas数据在某个列表里的数据

Published on Aug. 22, 2023, 12:11 p.m.

原始的 Pandas dataframe:

df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]})
df

     A   B
0    5   1
1    6   2
2    3   3
3    4   5

判断单个数据符合:

x = df[df['A'] == 3]
x

     A   B
2    3   3

如何实现以下:

list_of_values = [3,6]
# 错误写法
y = df[df['A'] in list_of_values]

获取结果如下:

     A    B
1    6    2
2    3    3

解决方案


In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

参考链接

https://stackoverflow.com/questions/12096252/use-a-list-of-values-to-select-rows-from-a-pandas-dataframe

Tags: