Pandas筛选一列,但仅当另一列小于指定值时。

huangapple go评论66阅读模式
英文:

Pandas filtering one column but only if another column is less than a specified value

问题

我有一个类似这样的数据框:

C1 C2
100 10
25 8
67 4
0 4
0 1
67 0

我尝试应用一个筛选条件,如果C2中的值大于2,则移除C1中的0值。目前我的筛选条件给出了如下输出:

C1 C2
100 10
25 8
67 4

而我想要的输出应该是:

C1 C2
100 10
25 8
67 4
0 1
67 0

我的当前筛选条件是:

(df['C1'] != 0) & (df['C2'] > 2)

但我也尝试过:

(df['C1'] > 0) & (df['C2'] > 2)

结果是相同的。

英文:

I have a dataframe that looks like this:

C1 C2
100 10
25 8
67 4
0 4
0 1
67 0

And I'm trying to apply a filter that removes 0 values in C1 but only if the values in C2 are greater than two. At the moment my filter gives me an output that looks like this:

C1 C2
100 10
25 8
67 4

whilst the output I want would be:

C1 C2
100 10
25 8
67 4
0 1
67 0

my filter currently is:

(df['C1'] != 0) & (df['C2'] > 2)

but I've also tried

(df['C1'] > 0) & (df['C2'] > 2)

which gave me the same result

答案1

得分: 2

使用两个掩码进行布尔索引

out = df[~(df['C1'].eq(0) & df['C2'].gt(2))]

或者:

out = df[df['C1'].ne(0) | df['C2'].le(2)]

输出:

    C1  C2
0  100  10
1   25   8
2   67   4
4    0   1
5   67   0

可复现的输入:

df = pd.DataFrame({'C1': [100, 25, 67, 0, 0, 67],
                   'C2': [10, 8, 4, 4, 1, 0]})
英文:

Use boolean indexing with two masks:

out = df[~(df['C1'].eq(0) & df['C2'].gt(2))]

Or:

out = df[df['C1'].ne(0) | df['C2'].le(2)]

Output:

    C1  C2
0  100  10
1   25   8
2   67   4
4    0   1
5   67   0

Reproducible input:

df = pd.DataFrame({'C1': [100, 25, 67, 0, 0, 67],
                   'C2': [10, 8, 4, 4, 1, 0]})

答案2

得分: 2

这应该有效。

new_df = df.loc[~((df.C1 == 0) & (df.C2 > 2))]

这也应该有效。

new_df = df.loc[(df.C1 != 0) | (df.C2 <= 2)]
英文:

This should work.

new_df = df.loc[~((df.C1 == 0) &amp; (df.C2 &gt; 2))]

as should this one.

new_df = df.loc[(df.C1 =! 0) | (df.C2 &lt;= 2))]

huangapple
  • 本文由 发表于 2023年7月6日 18:07:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定