【问题标题】:take mean of data within the same day pandas取同一天数据的平均值 pandas
【发布时间】:2018-01-14 18:41:11
【问题描述】:

我有一个数据框df,其中包含测量日期和测量值(durationkm

df
Out[20]: 
                          Date duration km
0   2015-03-28 09:07:00.800001    0      0
1   2015-03-28 09:36:01.819998    1      2
2   2015-03-30 09:36:06.839997    1      3
3   2015-03-30 09:37:27.659997    nan    5
4   2015-04-22 09:51:40.440003    3      7
5   2015-04-23 10:15:25.080002    0      nan

如何计算每天的平均时长和公里数?我想使用 groupby 和日期来取行的平均值...

【问题讨论】:

    标签: python pandas group-by


    【解决方案1】:

    我觉得你需要resample:

    cols = df.columns.difference(['Date'])
    #if possible convert to float
    df[cols] = df[cols].astype(float)
    

    #if astype failed, because non numeric data, convert them to NaNs
    df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
    
    #if mixed dtypes
    df[cols] = df[cols].astype(str).astype(float)
    #alternatively 
    #df[cols] = df[cols].astype(str).apply(pd.to_numeric, errors='coerce')
    

    df = df.resample('d', on='Date').mean().dropna(how='all')
    print (df)
                duration   km
    Date                     
    2015-03-28       0.5  1.0
    2015-03-30       1.5  4.0
    2015-04-22       3.0  7.0
    2015-04-23       0.0  0.0
    

    或者:

    df = df.set_index('Date').groupby(pd.Grouper(freq='d')).mean().dropna(how='all')
    print (df)
                duration   km
    Date                     
    2015-03-28       0.5  1.0
    2015-03-30       1.5  4.0
    2015-04-22       3.0  7.0
    2015-04-23       0.0  0.0
    

    【讨论】:

    • 您好,感谢您的回答。最后一部分 .dropna(how='all') 到底是做什么的?
    • 有问题 resample 返回连续日期时间索引的所有缺失值。如果缺少某个日期,则添加值并由NaNs 填充。 dropna 删除所有带有NaNs 的行。 John Galt回答不需要,但是没有datetimeindex,只有python日期填充的索引(可能有问题,也可能没有)
    • 是的,完全正确。在 pandas 中意味着像 nanmean 一样工作 - 省略 nans。
    • 不幸的是,我现在正在度假,只能打电话。所以更好的是创造新的问题。谢谢。
    • 假期愉快! :)
    【解决方案2】:

    使用groupby

    In [896]: df.groupby(df.Date.dt.date).mean()
    Out[896]:
                duration   km
    Date
    2015-03-28       0.5  1.0
    2015-03-30       1.5  4.0
    2015-04-22       3.0  7.0
    2015-04-23       0.0  0.0
    

    【讨论】:

    • 谢谢!但是我得到 DataError: No numeric types to aggregate
    • 您的kmduration 列可能是字符串类型的?
    • 它是 numpy.float64
    • 试试df.convert_objects(convert_numeric=True).groupby(df.Date.dt.date).mean()?
    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 2015-04-03
    • 2021-06-14
    • 2022-08-17
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 2019-02-15
    相关资源
    最近更新 更多