Init5 God
Init5 God

Reputation: 11

Pandas (python) Extract sum of values in different rows using one column as filter

.Im learning data analysis and i would like to do the following. Im using pandas with google collaboratory:

I have next table:

name A1 A2 A3
First a c d
Second b a a
First a c d
First a c d
First a c d
Second b a a

I wish to sum every repeated value in columns "A1" to "A3" using the "name" (index) column as a filter. So the result i want is something like:

name a b c d
First 4 0 4 4
Second 4 2 0 0

I have tried: data.groupby('A1').size() but first i dont know how to tell pandas to show me those result divides by group of the names in column 2

Upvotes: 0

Views: 77

Answers (1)

BeRT2me
BeRT2me

Reputation: 13242

Given:

       A1 A2 A3
name
First   a  c  d
Second  b  a  a

Doing:

out = (df.apply(lambda x: x.value_counts(), axis=1, result_type='expand')
         .fillna(0)
         .astype(int))
print(out)

Output:

        a  b  c  d
name
First   1  0  1  1
Second  2  1  0  0

Upvotes: 1

Related Questions