pandas 使用 df.query() 从 DataFrame 中提取行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45978225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:21:39  来源:igfitidea点击:

Using df.query() to extract rows from a DataFrame

pythonpandasdataframe

提问by neha

I have a DataFrame dfwhich contain three columns: ['mid','2014_amt','2015_amt']

我有一个包含三列的 DataFrame df['mid','2014_amt','2015_amt']

I want to extract rows of a particular merchant. For example, consider my data is:

我想提取特定商家的行。例如,考虑我的数据是:

df['mid'] = ['as','fsd','qww','fd']
df['2014_amt] = [144,232,45,121]
df['2015_amt] = [676,455,455,335]

I want to extract the whole rows corresponding to mid = ['fsd','qww']How is this best done? I tried with the below code:

我想提取对应于mid = ['fsd','qww']如何最好地完成的整行?我尝试使用以下代码:

df.query('mid== "fsd"')

If I want to run a loop, how can I use the above code to extract rows for specified values of mid?

如果我想运行一个循环,我如何使用上面的代码来提取指定值的行mid

for val in mid:
           print df.query('mid' == "val"')

This is giving an error, as valis not specified.

这是一个错误,因为val没有指定。

回答by piRSquared

Option 1

选项1

df.query('mid in ["fsd", "qww"]')

   mid  2014_amt  2015_amt
1  fsd       232       455
2  qww        45       455


Option 2

选项 2

df[df['mid'].isin(['fsd', 'qww'])]

   mid  2014_amt  2015_amt
1  fsd       232       455
2  qww        45       455