Skip to main content
 首页 » 编程设计

python & pandas -- 从 2 列值生成多列

2025年05月04日12Terrylee

我想从这个开始..

type  cost 
dog   5 
dog   2 
cat   4 
rat   6 

为此..

dog cat rat 
 5   0   0 
 2   0   0 
 0   4   0 
 0   0   6 

这几乎可以工作...

pd.concat([ tbl1['type'].astype(str) == x for x in ['dog','cat','rat']], 1, keys=['dog','cat','rat']) 

但是......我得到了一个真/假值表

我试图避免使用 for 循环来生成 N 个列,因为实际上我可能需要 100 多个列用于“类型”列中的不同值

请您参考如下方法:

你可以使用 pivot_table

df.pivot_table(values='cost', index=df.index, columns='type', aggfunc='first').fillna(0) 
 
type  cat  dog  rat 
0       0    5    0 
1       0    2    0 
2       4    0    0 
3       0    0    6