【问题标题】:Mean of sum in a DataFrame with Python使用 Python 在 DataFrame 中求和的平均值
【发布时间】:2016-12-25 05:36:53
【问题描述】:

我创建了一个 DataFrame df1,其中包含一周中每一天的每台机器的激活时间数。

machine1    38696 non-null float64
machine3    38697 non-null float64
machine5    38695 non-null float64
machine6    38695 non-null float64
machine7    38693 non-null float64
machine8    38696 non-null float64
date                      38840 non-null datetime64[ns]
day_of_week               38840 non-null object
dtypes: datetime64[ns](2), float64(6), object(1)
memory usage: 2.7+ MB



Machine1 Machine3 Machine5 Machine6 Machine7 Machine8 date day_of_week
90.0 90.0 90.0 90.0 90.0 90.0 2015-07-31 Fri 
0.0 0.0 0.0 0.0 0.0 0.0 2015-07-31 Mon
0.0 0.0 0.0 0.0 0.0 0.0 2015-07-31 Tues
0.0 0.0 0.0 0.0 0.0 0.0 2015-07-31 Fri 
0.0 0.0 0.0 0.0 0.0 0.0 2015-07-31 Tues

我尝试创建另一个 DataFrame,它为每台机器提取每天的激活平均值。例如:

            Machine1 Machine3 Machine5 Machine6 Machine7 Machine8
Mon           0          ..     ..       ..       ..        ..
Tue           0
wed           0
thu            0
fri           45  

你能帮助我以最聪明的方式实现这一目标吗?

【问题讨论】:

    标签: python pandas dataframe group-by mean


    【解决方案1】:

    你可以使用的IIUC:

    print (df.groupby('day_of_week').mean())
                 Machine1  Machine3  Machine5  Machine6  Machine7  Machine8
    day_of_week                                                            
    Fri              45.0      45.0      45.0      45.0      45.0      45.0
    Mon               0.0       0.0       0.0       0.0       0.0       0.0
    Tues              0.0       0.0       0.0       0.0       0.0       0.0
    

    如果需要带复位索引的输出:

    print (df.groupby('day_of_week', as_index=False).mean())
      day_of_week  Machine1  Machine3  Machine5  Machine6  Machine7  Machine8
    0         Fri      45.0      45.0      45.0      45.0      45.0      45.0
    1         Mon       0.0       0.0       0.0       0.0       0.0       0.0
    2        Tues       0.0       0.0       0.0       0.0       0.0       0.0
    

    【讨论】:

    • 我不确定是否理解您的问题。为什么在您的示例中是45Monday 中?是错字吗?
    猜你喜欢
    • 2021-12-24
    • 2021-09-09
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多