简体   繁体   English

按多个列值过滤熊猫数据框

[英]filter pandas dataframe by several column values

I would like to filter a df by several columns, is it possible to do it in one line?我想按几列过滤 df,是否可以在一行中完成?

so far I did it over many lines:到目前为止,我做了很多行:

mini_df = df[df['col1']==0] mini_df = mini_df[mini_df['col2']==1] mini_df = df[df['col1']==0] mini_df = mini_df[mini_df['col2']==1]

but if I do mini_df = df[df['col1']==0 and df['col2']==1] it does not work.但是如果我做mini_df = df[df['col1']==0 and df['col2']==1]它不起作用。 since I want to have many such filters would be good to be able to do them in one line.因为我想要很多这样的过滤器,所以能够在一行中完成它们会很好。

you were close, try to put every filter in brackets () and "&" instead of "and":你很接近,尝试将每个过滤器放在括号 () 和“&”而不是“and”中:

mini_df = df[(df['col1']==0) & (df['col2']==1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM