[英]create a new dataframes with rows from another dataframe with specific columns values
I would like to create a new pandas dataframe from an existing dataframe with only rows where specific columns values are bigger than x.我想从现有的 dataframe 创建一个新的 pandas dataframe,其中只有特定列值大于 x 的行。 For example:例如:
df = A B C
0 1 0 2
1 2 1 3
2 3 3 0
3 4 2 5
I want to create new_df with only the rows where the values of columns B and C are bigger than 0 which means我想只使用列 B 和 C 的值大于 0 的行创建 new_df
new_df = A B C
0 2 1 3
1 4 2 5
I used the command:我使用了命令:
new_df = df.loc[df['B'] > 0 & df['C'] > 0]
but it doesn't work但它不起作用
You almost had it.你几乎拥有它。 Use parenthesis to enclose conditions:使用括号括起来条件:
new_df = df.loc[(df['B'] > 0) & (df['C'] > 0)]
The binary operators &
and |
二元运算符&
和|
take precedence over equalities/inequalities.优先于平等/不平等。 So what you were doing was equivalent to:所以你所做的相当于:
new_df = df.loc[(df['B'] > (0 & df['C'])) > 0]
You can use this:你可以使用这个:
df[(df[['B', 'C']] > 0).all(axis=1)]
Output: Output:
A B C
1 2 1 3
3 4 2 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.