Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum all possible combinations in pandas dataframe

I have a df containing several columns, but two of them look like:

number output colour
1         1    green
2         1    red
3         1    orange
4         0    green
5         1    green

I need to find all possible combinations and the number of occurences there so I expect something like

1green    2
1red      1
1orange   1
0green    1

Using this python: Combination of two Columns I found all possible combinations, but I do not know how to do the sum. Or is there any solution to do it in one step?

THank you

like image 965
ZuzanaTelefony Avatar asked Mar 01 '23 16:03

ZuzanaTelefony


2 Answers

Try:

pd.value_counts([*zip(df.output, df.colour)])

(1, green)     2
(0, green)     1
(1, orange)    1
(1, red)       1
dtype: int64
like image 151
piRSquared Avatar answered Mar 05 '23 19:03

piRSquared


Use Series.value_counts with joined columns:

s = (df.output.astype(str) + df.colour).value_counts()
print (s)
1green     2
1red       1
0green     1
1orange    1
dtype: int64

Or is possible use GroupBy.size:

s = df.groupby(['output','colour']).size()
print (s)
output  colour
0       green     1
1       green     2
        orange    1
        red       1
dtype: int64

Or DateFrame.value_counts

s = df[['output','colour']].value_counts()
print (s)
output  colour
1       green     2
0       green     1
1       orange    1
        red       1
dtype: int64

Last for DataFrame use:

s = s.reset_index(name='count')

EDIT:

For all combinations use:

s = df.groupby(['output','colour']).size().unstack(fill_value=0).stack()
print (s)
output  colour
0       green     1
        orange    0
        red       0
1       green     2
        orange    1
        red       1
dtype: int64

s = df[['output','colour']].value_counts().unstack(fill_value=0).stack()
print (s)
output  colour
0       green     1
        orange    0
        red       0
1       green     2
        orange    1
        red       1
dtype: int64
like image 34
jezrael Avatar answered Mar 05 '23 18:03

jezrael