[英]Python - group by columns A + B and count row values for columns C for each unique occurrence of A + B
我讨厌问,但是我已经搜索了许多小时来寻找解决此问题的方法。 我与熊猫关系密切,但距离不够。 我知道这一定有可能使我发疯! 所以我有一个像这样的data_frame:
df = pd.DataFrame(
{'Path': ['Yellow','Yellow','Blue','Green','Yellow','Blue','Yellow','Yellow'],
'Type': ['Image','Video','Image','Video','Video','Video','Image','Image'],
'Category': [A,A,B,A,B,A,C,C],
},
我努力了:
A = df[(df['Category'] == 'A') & (df['Type'] == 'Image')]
A = A.groupby(['Path']).size().reset_index(name='Count of A')
但这只会一次返回一个“类别”的计数及其每个唯一“路径”的“类型”。 理想情况下,我想对数据进行分组,以便输出类似于此的内容:
Path | Type | Count of A | Count of B | Count of C |
Yellow | Image | 1 | | 2 |
| Video | 1 | 1 | |
Green | Image | | | |
| Video | 1 | | |
Blue | Image | | 1 | |
| Video | 1 | | |
即使我一次可以做一个Path也会比我当前输出的更好。
我希望有人能看到解决方案并使我摆脱困境!?
仍在使用groupby
+ value_counts
df.groupby(['Path','Type']).Category.apply(pd.value_counts).unstack().fillna('')
Out[121]:
A B C
Path Type
Blue Image 1
Video 1
Green Video 1
Yellow Image 1 2
Video 1 1
或者我们使用pivot_table
pd.pivot_table(df.reset_index(),index=['Path','Type'],columns=['Category'],values='index',aggfunc='count')
Out[123]:
Category A B C
Path Type
Blue Image NaN 1.0 NaN
Video 1.0 NaN NaN
Green Video 1.0 NaN NaN
Yellow Image 1.0 NaN 2.0
Video 1.0 1.0 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.