[英]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.