【问题标题】:Performing an "if any true" check on boolean column in DataFrame?对 DataFrame 中的布尔列执行“如果有的话”检查?
【发布时间】:2020-03-03 15:36:28
【问题描述】:

我想知道是否有一种方法可以在不遍历 DF 行的情况下汇总布尔值。我有这样的情况:

Label | Attribute  
Item1 | False  
Item1 | False  
Item2 | False  
Item2 | True  
Item3 | True  
Item3 | False  

我想这样总结一下:

Label | Attribute  
Item1 | False  
Item2 | True  
Item3 | True  

带有某种“如果有的话是真的”的论点。我一直在为其他类型的属性编写一个包含 groupby 和方法(max)等的汇总表,我可以通过迭代创建一个汇总,但如果有更简单的方法,我当然宁愿避免。

【问题讨论】:

  • 试试df.groupby('Label')['Attribute'].any()
  • 您可以执行与@ChrisA 建议的df.set_index('Label').Attribute.any(level=0) 相同的操作
  • 感谢@ChrisA 和 piRSquared,他们的工作完美!
  • 感谢 ChrisA 和 @piRSquared,他们工作得很好!

标签: python pandas dataframe boolean summary


【解决方案1】:

您还可以使用describe() 方法,该方法对于汇总数据框很有用。

df.groupby('Label')['Attribute'].describe()

【讨论】:

    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 2019-10-15
    • 2018-11-25
    • 2012-11-28
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多