【问题标题】:Iterating with conditions over Distinct Values in a Column使用条件对列中的不同值进行迭代
【发布时间】:2022-09-22 21:11:03
【问题描述】:

我有一个看起来像这样的数据集:

category value
A 1
A 0.5
A 0.33
B 0.5
B 0.33
C 5
C 0.33

对于每个类别,我想获取所有值 <= 0.5 的实例。我想为每个类别计算这些实例。

我理想的最终目标是拥有一个数据框或列表,其中包含每个类别的计数。

非常感谢你的帮助。

    标签: python pandas function loops for-loop


    【解决方案1】:

    您可以在值与 0.5 的比较的布尔系列上使用 groupby.sum

    out = df['value'].le(0.5).groupby(df['category']).sum()
    

    或者,使用boolean indexingvalue_counts

    df.loc[df['value'].le(0.5), 'category'].value_counts()
    

    输出:

    category
    A    2
    B    2
    C    1
    Name: value, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多