Python - 按 A + B 列分组,并为每次唯一出现的 A + B 计算 C 列的行值
Python - group by columns A + B and count row values for columns C for each unique occurrence of A + B
我不想问这个问题,但我已经搜索了很多小时来解决这个问题。我已经接近 Pandas 但还不够接近。这让我发疯,因为我知道这一定是可能的!
所以我有一个像这样的 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')
但这仅 returns 一次 'Category' 的计数及其 'Type' 每个唯一 'Path' 的计数。理想情况下,我想对数据进行分组,使其输出类似于以下内容:
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 | | |
即使我一次只能做一个路径,这也会比我目前输出的更好。
我希望有人能看到解决方案,让我摆脱痛苦!?
仍在使用 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
我不想问这个问题,但我已经搜索了很多小时来解决这个问题。我已经接近 Pandas 但还不够接近。这让我发疯,因为我知道这一定是可能的! 所以我有一个像这样的 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')
但这仅 returns 一次 'Category' 的计数及其 'Type' 每个唯一 'Path' 的计数。理想情况下,我想对数据进行分组,使其输出类似于以下内容:
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 | | |
即使我一次只能做一个路径,这也会比我目前输出的更好。
我希望有人能看到解决方案,让我摆脱痛苦!?
仍在使用 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