我在弄清楚如何按列分组行时遇到了麻烦。我的目标是计算列值分别为橙色和蓝色的“包装代码”的数量。
我正在处理数千行数据。这是数据的子集:
Country Package Code Color Type
US 100 Orange a
US 100 Orange b
US 100 Orange c
Mexico 200 Green d
US 300 Blue e
Canada 400 Red f
Germany 500 Red g
Germany 600 Blue h
所需输出:
Country Packages
US 2
Mexico 0
Canada 0
Germany 1
使用isin
+ nunique
+reindex
(df.loc[df.Color.isin(['Orange', 'Blue'])].groupby('Country')['Package Code']
.nunique().reindex(df.Country.unique(), fill_value=0)).to_frame('Total').reset_index()
Country Total
0 US 2
1 Mexico 0
2 Canada 0
3 Germany 1
以下是上面的命令,为了更好的可读性将其分解:
# Select rows where the color is Orange or Blue
u = df.loc[df.Color.isin(['Orange', 'Blue'])]
# Find the unique values for Package Code, grouped by Country
w = u.groupby('Country')['Package Code'].nunique()
# Add in missing countries with a value of 0
w.reindex(df.Country.unique(), fill_value=0).to_frame('Total').reset_index()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句