1
$\begingroup$
country   year    gender    measure               value0 ... value12
 A         2000    1         vaccinated_at_month   2      ... 1
 B         2000    1         vaccinated_at_month   13     ... 12
 A         2000    0         vaccinated_at_month   4      ... 3
 A         2000    9         vaccinated_at_month   5      ... 4
 B         2000    0         walked_at_month       3      ... 13
 C         2001    1         vaccinated_at_month   6      ... 5
 C         2001    0         vaccinated_at_month   3      ... 2

I want to be able to remove the gender column and collapse all values into sums based on the previous categorical columns.

I have tried

df_new = df.groupby(['country', 'year', 'gender', 'measure'])['value0', ... 'value12'].apply(lambda x : x.astype(float).sum())

However, df_new still preserves the gender column. I am trying to get this outcome:

country   year       measure               value0      ... value12
 A         2000       vaccinated_at_month   11 (=2+4+5) ... 8 (=1+3+4)
 B         2000       vaccinated_at_month   13          ... 12
 B         2000       walked_at_month       3           ... 13
 C         2001       vaccinated_at_month   9 (=6+3)    ... 7 (=5+2)
 C         2001       vaccinated_at_month   3           ... 2
$\endgroup$
0
$\begingroup$

This question is more appropriate at Stackoverflow since it is more of a programming question.

However, I think you almost got it working. Just remove gender from your groupby:

df_new = df.groupby(['country', 'year', 'measure'])['value0', ... 'value12'].apply(lambda x : x.astype(float).sum())
$\endgroup$
0
$\begingroup$

You can try this:

df_new = df.groupby(['country', 'year', 'measure'])['value0', '...', 'value12'].sum()
print(df_new)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.