计算跨日期列的平均值

2024-04-25 13:41:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含多个列的数据集,这些列的名称是日期。例如:

df = pd.DataFrame({'company': ['dell', 'microsoft', 'toshiba', 'apple'], 
               'measure': ['sales', 'speed', 'wait time', 'service'], 
               'category': ['laptop', 'tablet', 'smartphone', 'desktop'], 
               '10/6/2015': [234, 333, 456, 290], 
               '10/13/2015': [134, 154, 123, 177], 
               '10/20/2015': [57, 57, 63, 71]})

我想计算每个月的平均值。因此,对于上面的例子,我希望期望的结果是:

     company    measure    category  201510
0       dell      sales      laptop  141.66
1  microsoft      speed      tablet  181.33
2    toshiba  wait time  smartphone  214.00
3      apple    service     desktop  179.33

其中201510df中三个日期列的平均值。有没有一种方法可以使用多个日期列来实现这一点,比如说,groupby?任何帮助将不胜感激,我是一个完全的新手当谈到python。我应该使用时间序列方法还是有一种直接的方法通过pandas来实现这一点?你知道吗


Tags: 方法appledftimeservicecompanymicrosoftdell
1条回答
网友
1楼 · 发布于 2024-04-25 13:41:12

使用filterlike过滤列,然后将列转换为datetime,并使用groupby

s=df.filter(like='/')
s.columns=pd.to_datetime(s.columns).strftime('%Y-%m')
pd.concat([df,s.groupby(level=0,axis=1).mean()],axis=1)
Out[229]: 
     company    measure     ...     10/20/2015     2015-10
0       dell      sales     ...             57  141.666667
1  microsoft      speed     ...             57  181.333333
2    toshiba  wait time     ...             63  214.000000
3      apple    service     ...             71  179.333333
[4 rows x 7 columns]

相关问题 更多 >