[英]python pandas : group by several columns and count value for one column
我有df :
orgs feature1 feature2 feature3
0 org1 True True NaN
1 org1 NaN True NaN
2 org2 NaN True True
3 org3 True True NaN
4 org4 True True True
5 org4 True True True
现在我想计算每个功能的不同组织的数量。 基本上有一个df_Result这样的:
features count_distinct_orgs
0 feature1 3
1 feature2 4
2 feature3 2
有没有人知道如何做到这一点?
df1 = df.groupby('orgs')
.apply(lambda x: x.iloc[:,1:].apply(lambda y: y.nunique())).sum().reset_index()
df1.columns = ['features','count_distinct_orgs']
print (df1)
features count_distinct_orgs
0 feature1 3
1 feature2 4
2 feature3 2
aggregate
Series.nunique
另一个解决方案:
df1 = df.groupby('orgs')
.agg(lambda x: pd.Series.nunique(x))
.sum()
.astype(int)
.reset_index()
df1.columns = ['features','count_distinct_orgs']
print (df1)
features count_distinct_orgs
0 feature1 3
1 feature2 4
2 feature3 2
stack
解决方案有效,但返回警告:
C:\\Anaconda3\\lib\\site-packages\\pandas\\core\\groupby.py:2937: FutureWarning: numpy not_equal 将来不会检查对象身份。 比较没有返回与标识 (
is
)) 所建议的结果相同的结果,并且会发生变化。 inc = np.r_[1, val[1:] != val[:-1]]
df1 = df.set_index('orgs').stack(dropna=False)
df1 = df1.groupby(level=[0,1]).nunique().unstack().sum().reset_index()
df1.columns = ['features','count_distinct_orgs']
print (df1)
features count_distinct_orgs
0 feature1 3
1 feature2 4
2 feature3 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.