noob
noob

Reputation: 3811

Groupby for selecting multiple columns Pandas python

I have a table pandas dataframe df with 3 columns lets say:

[IN]:df
[OUT]:

Tree Name   Planted by Govt   Planted by College
A               Yes                No 
B               Yes                No
C               Yes                No 
C               Yes                No
A               No                 No 
B               No                 Yes
B               Yes                Yes
B               Yes                No
B               Yes                No  

Query:

How many trees were planted by govt and not by college for each type of tree. Govt: Yes, Pvt: No

Output needed:

1 Tree(s) 'A' were planted by govt and not by college
3 Tree(s) 'B' were planted by govt and not by college
2 Tree(s) 'C' were planted by govt and not by college

Can anyone please help

Upvotes: 1

Views: 711

Answers (2)

Antonios
Antonios

Reputation: 1939

Or we could use count

df[df['Planted by Govt'].eq('Yes')& df['Planted by College'].eq('No')].groupby('Tree Name').count()['Planted by Govt'].rename('PLanted only by Govt')

print(result)
Tree Name
A    1
B    3
C    2
Name: PLanted only by Govt, dtype: int64

Upvotes: 1

jezrael
jezrael

Reputation: 862681

First create boolean mask by compare both column chained with & for bitwise AND and then convert to numeric with aggregate sum:

s = df['Planted by Govt'].eq('Yes') & df['Planted by College'].eq('No')
out = s.view('i1').groupby(df['Tree Name']).sum()
#alternative
#out = s.astype(int).groupby(df['Tree Name']).sum()
print (out)
Tree Name
A    1
B    3
C    2
dtype: int8

Last for custom output use f-strings:

for k, v in out.items():
    print (f"{v} Tree(s) {k} were planted by govt and not by college")

    1 Tree(s) A were planted by govt and not by college
    3 Tree(s) B were planted by govt and not by college
    2 Tree(s) C were planted by govt and not by college

Another idea is create new column to original:

df['new'] = (df['Planted by Govt'].eq('Yes') & df['Planted by College'].eq('No')).view('i1')
print (df)
  Tree Name Planted by Govt Planted by College  new
0         A             Yes                 No    1
1         B             Yes                 No    1
2         C             Yes                 No    1
3         C             Yes                 No    1
4         A              No                 No    0
5         B              No                Yes    0
6         B             Yes                Yes    0
7         B             Yes                 No    1
8         B             Yes                 No    1

out = df.groupby('Tree Name')['new'].sum()
print (out)
Tree Name
A    1
B    3
C    2
Name: new, dtype: int8

Upvotes: 1

Related Questions