0

Currently, I have 52 columns represent weeks, I want to merge every 4 columns(4 weeks) into one month. So I need to merge and add to new column every 4 columns. How do I merge and add every 4 columns? Pandas.sum doesn't work for me as it added up all the columns.

w1 w2 w3 w4 ... w52

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

What I want:

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
    I had a similar question here: http://stackoverflow.com/questions/32722671/pandas-combining-multiple-columns-in-a-dataframe – ayhan Mar 02 '16 at 18:17

1 Answers1

0

try this:

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)
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419