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

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

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

问题

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

我的数据框:

  1. ID value
  2. A 3
  3. A 2
  4. A 0
  5. B 1
  6. B 1
  7. C 3
  8. C 3
  9. C 4
  10. D 0
  11. D 5
  12. D 5
  13. E 6
  14. E 7
  15. E 7
  16. F 3
  17. F 2

我的期望数据框将会是:

  1. ID value
  2. A 3
  3. A 2
  4. A 0
  5. B 1
  6. B 1
  7. D 0
  8. D 5
  9. D 5
  10. F 3
  11. 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

  1. ID value
  2. A 3
  3. A 2
  4. A 0
  5. B 1
  6. B 1
  7. C 3
  8. C 3
  9. C 4
  10. D 0
  11. D 5
  12. D 5
  13. E 6
  14. E 7
  15. E 7
  16. F 3
  17. F 2

my desired df would be

  1. ID value
  2. A 3
  3. A 2
  4. A 0
  5. B 1
  6. B 1
  7. D 0
  8. D 5
  9. D 5
  10. F 3
  11. F 2

答案1

得分: 3

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

  1. g = df['value'].eq(0).groupby(df['ID'])
  2. # group contains a 0
  3. m1 = g.transform('any')
  4. # group doesn't have size 3
  5. m2 = g.transform('size').ne(3)
  6. # keep if any of the condition above is met
  7. # this is equivalent to dropping if contains 0 AND size 3
  8. out = df[m1 | m2]

输出:

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

You can use boolean indexing with groupby operations:

  1. g = df['value'].eq(0).groupby(df['ID'])
  2. # group contains a 0
  3. m1 = g.transform('any')
  4. # group doesn't have size 3
  5. m2 = g.transform('size').ne(3)
  6. # keep if any of the condition above is met
  7. # this is equivalent to dropping if contains 0 AND size 3
  8. out = df[m1|m2]

Output:

  1. ID value
  2. 0 A 3
  3. 1 A 2
  4. 2 A 0
  5. 3 B 1
  6. 4 B 1
  7. 8 D 0
  8. 9 D 5
  9. 10 D 5
  10. 14 F 3
  11. 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:

确定