data = {'Col1': [1, 2, 2, 3, 1],
'Col2': ['A', 'B', 'B', 'A', 'C']}
df = pd.DataFrame(data)
我想要一本像这样的字典
{'Col1': {1:2, 2:2, 3:1},
'Col2': {'A':2, 'B':2, 'C':1}
不使用任何类型的循环、apply 或 agg 方法
我尝试过这样的事情:
count_matrix = df.stack().groupby(level=1).value_counts()
count_matrix = count_matrix.unstack(0)
count_matrix = count_matrix.to_dict()
但它不起作用,因为它们没有价值
一个可能的解决方案:
df.groupby(['Col1']).count().to_dict()['Col2']