日期列上的熊猫重新取样

use*_*044 4 python python-2.7 pandas

我有一个dataframe日期作为列.我想将每日的价值平均到每月的水平.我已经尝试过Time Grouper和Resample,但它不喜欢列名称是字符串,我似乎可以弄清楚如何使列成为类似的东西DatetimeIndex.

我的起始数据帧:

import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'], 
                  index=['A', 'B'])
Run Code Online (Sandbox Code Playgroud)

期望的输出:

   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5
Run Code Online (Sandbox Code Playgroud)

WeN*_*Ben 6

你可以用 resample

df.columns = pd.to_datetime(df.columns)
df.T.resample('M').mean().T
Out[409]: 
   2013-01-31  2013-02-28
A         1.5         3.5
B         5.5         7.5
Run Code Online (Sandbox Code Playgroud)

或者groupby一个

axis=1 
df.groupby(pd.to_datetime(df.columns).to_period('M'),1).mean()
Out[412]: 
   2013-01  2013-02
A      1.5      3.5
B      5.5      7.5
Run Code Online (Sandbox Code Playgroud)