KIDJourney
KIDJourney

Reputation: 1220

How can I aggregate on multiple columns in pandas?

Now i have some data looks like below :

    song_id                             artist_id                     0 days 1 days 2 days  
1   0919b5ed4ce2649f61bcc6c21fadab12    0c80008b0a28d356026f4b1097041689    0   0   0
2   8a0777df37bf6a0f3384d63a47d4d21b    0c80008b0a28d356026f4b1097041689    0   1   0
3   b61bc45712ee40c3f4a37dd4d063ad52    0c80008b0a28d356026f4b1097041689    0   0   0
4   a2fbe29da3a760d7467b8a7b3247a9c8    0c80008b0a28d356026f4b1097041689    0   0   1
5   b5e92cb9ff2126189c19305cf148b25d    0c80008b0a28d356026f4b1097041689    0   0   0

And I want to group them by artist_id and aggregate the sum on 0 days , 1 days and 2 days , and get result like that .

        artist_id                      0 days 1 days 2 days
0       0c80008b0a28d356026f4b1097041689    0   1   1

I tried

df.groupby('artist_id').sum()

But it raise an error .

TypeError: Cannot compare type 'Timedelta' with type 'str'

df.info shows:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 10842 entries, 0 to 10841
Columns: 185 entries, song_id to 182 days 00:00:00
dtypes: float64(183), object(2)
memory usage: 15.4+ MB

How can I solve it using pandas's way ?

Any help is welcomed .

Upvotes: 1

Views: 125

Answers (2)

jezrael
jezrael

Reputation: 862731

You can use astype:

df.columns = df.columns.astype(str)

Upvotes: 1

KIDJourney
KIDJourney

Reputation: 1220

Thanks everyone .

After applying

df.columns = map(str,df.columns)

The step

df.groupby('artist_id').sum()

works .

Upvotes: 0

Related Questions