2016-03-02 156 views
0

目前,我有52列表示星期,我想每4列(4周)合并成一个月份。所以我需要合并并添加到新列每4列。我如何合并和添加每4列? Pandas.sum不适合我,因为它将所有列加起来。熊猫合并,并添加列

w1 w2 w3 w4 ... w52 

1 0 0 1 ... 0 
0 1 0 0 ... 1 

我想要什么:

w1 w2 w3 w4 ... w52 1 2 3 4 ... 12 

1 0 0 1  0 2 4 5 2 ... 4 
0 1 0 0 ... 0 1 0 3 4 ... 5 
+1

我也有类似的问题在这里:http://stackoverflow.com/questions/32722671/pandas-combining-多列-IN-A-数据帧 – ayhan

回答

0

试试这个:

t = df.T 
t['week'] = (t.index.str[1:].astype(int) - 1).map('{:02d}'.format) 
t['month'] = pd.to_datetime(t['week'] + '-0', format='%W-%w').dt.month 

del t['week'] 

print(t.groupby('month').sum().T)