【问题标题】:Average value and sum of strings for each day每天字符串的平均值和总和
【发布时间】:2020-10-14 20:44:28
【问题描述】:

我有一个包含 3 列的数据框。我正在使用 python / pandas。

     date         id         my_value1      my_value2
0    31.07.20     128909      0.098333      positive
1    31.07.20     128914      0.136364      positive
3    31.07.20     853124     -0.025000      negative
4    30.07.20     123456     -1.000000      neutral
...

第一列包含从 06.02.20 到 31.07.20 之间的日期(可以解析为任何其他形式),其中缺少一些日期。如您所见,每天都会出现多次。

my_value1 列包含一个介于 1 和 -1 之间的浮点数。

my_value2 列包含字符串“positive”、“negative”或“neutral”。

我想要的是一个新的数据框,其中包含每天“my_value1”的平均值和“my_value2”的每个值的总和,如下所示:

     date         average_value1     sum_positive     sum_negative     sum_neutral
0    31.07.20      0.1               1532             2153             5321
1    30.07.20      0.2               2153             5321             1532
3    29.07.20     -0.3               1234             1234             1234
...

感谢任何帮助!

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    如果原始DataFrame的索引不重要,你可以这样做

    encoded_df = pd.get_dummies(df, prefix="", prefix_sep="", columns=["my_value2"])
    output = encoded_df.groupby("date").agg(
        average_value1 = pd.NamedAgg("my_value1", "mean"),
        sum_positive = pd.NamedAgg("positive", "sum"),
        sum_negative = pd.NamedAgg("negative", "sum"),
        sum_neutral = pd.NamedAgg("neutral", "sum")
    ).reset_index()
    

    输出:

           date  average_value1  sum_positive  sum_negative  sum_neutral
    0  30.07.20       -1.000000             0             0            1
    1  31.07.20        0.069899             2             1            0 
    

    【讨论】:

      【解决方案2】:

      这就是我要走的路:

      from io import StringIO
      import pandas as pd
      # read data
      df = pd.read_csv(StringIO("""    date         id         my_value1      my_value2
      0    31.07.20     128909      0.098333      positive
      1    31.07.20     128914      0.136364      positive
      3    31.07.20     853124     -0.025000      negative
      4    30.07.20     123456     -1.000000      neutral
      """), sep='\s+')
      
      df.date = pd.to_datetime(df.date)
      df.set_index('date', inplace=True)
      # obtain daily average
      df_avg = df.resample('D').my_value1.mean().to_frame('average')
      # obtain the counts
      df_cnt = df.resample('D').my_value2.value_counts()
      df_cnt = df_cnt.to_frame()
      df_cnt = df_cnt.unstack()
      df_cnt = df_cnt.droplevel(level=0, axis=1)
      # join the two dataframes
      df_avg.join(df_cnt)
      # The desired output
          average negative    neutral positive
      date                
      2020-07-30  -1.000000   NaN 1.0 NaN
      2020-07-31  0.069899    1.0 NaN 2.0
      

      【讨论】:

        【解决方案3】:

        试试这个:

        tmp1 = df.groupby('date')['my_value1'].mean().to_frame('average_value1')
        
        tmp2 = (
            df.groupby(['date', 'my_value2'])
                ['my_value1'].sum()
                .unstack()
                [['positive', 'negative', 'neutral']]
        )
        tmp2.columns = 'sum_' + tmp2.columns
        
        result = tmp1.join(tmp2)
        

        【讨论】:

        • 看起来像它的工作,但不是作为数字的总和,该列包含一个长字符串,例如“积极积极积极积极...”。你知道一个快速解决方法吗?
        • 我将其更改为大写,因为它在我的数据中实际上是大写的。但所有其他列名都适合。
        猜你喜欢
        • 2019-02-10
        • 1970-01-01
        • 2018-12-19
        • 1970-01-01
        • 1970-01-01
        • 2022-11-13
        • 1970-01-01
        • 1970-01-01
        • 2022-12-10
        相关资源
        最近更新 更多