pandas: filter rows of DataFrame with operator cha

2019-01-01 04:22发布

Most operations in pandas can be accomplished with operator chaining (groupby, aggregate, apply, etc), but the only way I've found to filter rows is via normal bracket indexing

df_filtered = df[df['column'] == value]

This is unappealing as it requires I assign df to a variable before being able to filter on its values. Is there something more like the following?

df_filtered = df.mask(lambda x: x['column'] == value)

标签: python pandas
14条回答
人气声优
2楼-- · 2019-01-01 05:25

You can also leverage the numpy library for logical operations. Its pretty fast.

df[np.logical_and(df['A'] == 1 ,df['B'] == 6)]
查看更多
浮光初槿花落
3楼-- · 2019-01-01 05:27

This is unappealing as it requires I assign df to a variable before being able to filter on its values.

df[df["column_name"] != 5].groupby("other_column_name")

seems to work: you can chain the [] operator as well. Maybe they added it since you asked the question.

查看更多
登录 后发表回答