[英]How to merge multiple columns and add a reference column of headings in pandas
[英]Pandas merge and add columns
目前,我有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
尝试这个:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.