我想按组分组并删除形状为3且列中的值均不包含零的组。

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

I want to groupby and drop groups if the shape is 3 and non of the values from a column contains zero

问题

我想按条件分组并删除满足两个条件的分组(形状为3且列A不包含零)。

我的数据框:

ID  value
A    3
A    2
A    0
B    1
B    1
C    3
C    3
C    4
D    0
D    5
D    5
E    6
E    7
E    7
F    3
F    2

我的期望数据框将会是:

ID  value
A    3
A    2
A    0
B    1
B    1
D    0
D    5
D    5
F    3
F    2
英文:

I want to groupby and drop groups if it satisfies two conditions (the shape is 3 and column A doesn't contain zeros).

My df

ID  value
A    3
A    2
A    0
B    1
B    1
C    3
C    3
C    4
D    0
D    5
D    5
E    6
E    7
E    7
F    3
F    2

my desired df would be

ID  value
A    3
A    2
A    0
B    1
B    1
D    0
D    5
D    5
F    3
F    2

答案1

得分: 3

你可以在groupby操作中使用布尔索引:

g = df['value'].eq(0).groupby(df['ID'])

# group contains a 0
m1 = g.transform('any')
# group doesn't have size 3
m2 = g.transform('size').ne(3)

# keep if any of the condition above is met
# this is equivalent to dropping if contains 0 AND size 3
out = df[m1 | m2]

输出:

   ID  value
0   A      3
1   A      2
2   A      0
3   B      1
4   B      1
8   D      0
9   D      5
10  D      5
14  F      3
15  F      2
英文:

You can use boolean indexing with groupby operations:

g = df['value'].eq(0).groupby(df['ID'])

# group contains a 0
m1 = g.transform('any')
# group doesn't have size 3
m2 = g.transform('size').ne(3)

# keep if any of the condition above is met
# this is equivalent to dropping if contains 0 AND size 3
out = df[m1|m2]

Output:

   ID  value
0   A      3
1   A      2
2   A      0
3   B      1
4   B      1
8   D      0
9   D      5
10  D      5
14  F      3
15  F      2

huangapple
  • 本文由 发表于 2023年2月7日 01:28:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364642.html
匿名

发表评论

匿名网友

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

确定