1
$\begingroup$

I have a pandas dataframe as following:

df = pd.DataFrame({
    'Date': ['2017-1-1', '2017-1-1', '2017-1-2', '2017-1-2', '2017-1-3'],
    'Groups': ['one', 'one', 'one', 'two', 'two'], 
    'data1': range(1, 6),
    'data2': range(10, 15})

Output:

    Date      Groups     data1    data2
0  2017-1-1    one       1        10
1  2017-1-1    one       2        11
2  2017-1-2    one       3        12
3  2017-1-2    two       4        13
4  2017-1-3    two       5        15

I would like the output to look like this:

    Date      Groups     sum of data1    sum of data2
0  2017-1-1    one       6                33
1  2017-1-2    two       9                28

I can groupby "Group" and agg.(sum) either data columns, but couldn't do 2 simultaneously. How can I do this?

Thanks.

$\endgroup$
2
$\begingroup$

IIUC:

In [5]: (df.groupby("Groups", as_index=False)
           .agg({"Date":"first", "data1":"sum", "data2":"sum"}))
Out[5]:
  Groups      Date  data1  data2
0    one  2017-1-1      6     33
1    two  2017-1-2      9     27
| improve this answer | |
$\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.