我能够像这样实现您想要的输出:
from collections import Counter
import pandas as pd
df = pd.DataFrame({'A':[500,500,300,400,400,300],'B':[10,10,20,10,20,30]})
inp = df.groupby('A')['B'].agg(Counter).to_frame()
out = pd.DataFrame.from_records(inp['B'].tolist(), index=inp.index).fillna(0).T
输出:
A 300 400 500
20 1.0 1.0 0.0
30 1.0 0.0 0.0
10 0.0 1.0 2.0
groupyby/Counter 计算 A 中每个值中 B 中值出现的次数..然后第二步将字典列解压到数据帧中
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句