This question already has answers here:
How to filter Pandas dataframe using 'in' and 'not in' like in SQL

(8个答案)



Use a list of values to select rows from a pandas dataframe

(1个答案)


2年前关闭。




我有一个Python pandas DataFrame rpt:
rpt
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231')
Data columns:
STK_ID                    47518  non-null values
STK_Name                  47518  non-null values
RPT_Date                  47518  non-null values
sales                     47518  non-null values

我可以像这样过滤库存ID为'600809'的行:rpt[rpt['STK_ID'] == '600809']
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 25 entries, ('600809', '20120331') to ('600809', '20060331')
Data columns:
STK_ID                    25  non-null values
STK_Name                  25  non-null values
RPT_Date                  25  non-null values
sales                     25  non-null values

我想将一些股票的所有行放在一起,例如['600809','600141','600329']。这意味着我想要这样的语法:
stk_list = ['600809','600141','600329']

rst = rpt[rpt['STK_ID'] in stk_list] # this does not works in pandas

由于 Pandas 不接受上述命令,如何实现目标?

最佳答案

使用isin方法:
rpt[rpt['STK_ID'].isin(stk_list)]

07-27 13:16