我有一个 table pandas dataframe df 有 3 列让我们说:
[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
查询:
每种树种有多少棵树是由政府而非大学种植的。政府:是,私有(private):否
需要的输出:
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
谁能帮忙
最佳答案
首先通过比较用 &
链接的两个列来创建 bool 掩码以进行按位 AND
,然后使用聚合 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
自定义输出的最后一个使用 f-string
s:
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
另一个想法是为原始创建新列:
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
关于python - 用于选择多列 Pandas python 的 Groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58075544/