【问题标题】:Calculating mean of column based on the occurence of a number in another column Pandas dataframe Python根据另一列 Pandas 数据框 Python 中出现的数字计算列的平均值
【发布时间】:2022-01-09 04:09:41
【问题描述】:

我有一个如下所示的 Pandas 数据框。我要做的是计算 s2 列的平均值,每次在 s1 中出现“5”。

s1  s2
5   0.5
1   0.43
5   1
5   1

在这种情况下,5 出现了 3 次,因此我们取 0.5+1+1=0.83 的平均值。 有人可以帮我计算一下吗?谢谢!

【问题讨论】:

    标签: python pandas dataframe conditional-statements


    【解决方案1】:

    试试这个

    df[df['s1']==5]['s2'].mean()
    

    【讨论】:

      【解决方案2】:
      mean = df.loc[df['s1'] == 5, 's2'].mean()
      

      输出:

      0.8333333333333334
      

      【讨论】:

        【解决方案3】:

        如果你想要上面的答案分解,试试这个 -

        import pandas as pd
          
        data = [[5, 0.5], [1, .43], [5, 1], [5, 1]]
          
        df = pd.DataFrame(data, columns = ['S1', 'S2'])
        
        df = df.loc[df['S1'] == 5]
        
        df["S2"].mean()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-10-14
          • 2022-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多