首页 > 解决方案 > 熊猫列重新格式化

问题描述

有什么快速的方法可以实现以下输出吗?

输入:

Code Items
123 eq-hk
456 ca-eu; tp-lbe
789 ca-us
321 go-ch
654 ca-au; go-au
987 go-jp
147 co-ml; go-ml
258 ca-us
369 ca-us; ca-my
741 ca-us
852 ca-eu
963 ca-ml; co-ml; go-ml

输出:

Code eq   ca    go    co    tp
123  hk             
456       eu          lbe
789       us            
321             ch      
654       au    au      
987             jp      
147             ml     ml   
258       us            
369       us,my         
741       us            
852       eu            
963       ml     ml    ml

我再次陷入循环和一个非常丑陋的代码使其工作。如果有一种优雅的方式来实现这一点?

谢谢!

标签: pythonpandas

解决方案


这有点复杂

(df.set_index('Code')
   .Items.str.split(';',expand=True)
   .stack()
   .str.split('-',expand=True)
   .set_index(0,append=True)[1]
   .unstack()
   .fillna('')
   .sum(level=0))

0       ca  co  eq  go   tp
Code                       
123             hk         
147         ml      ml     
258     us                 
321                 ch     
369   usmy                 
456     eu              lbe
654     au          au     
741     us                 
789     us                 
852     eu                 
963     ml  ml      ml     
987                 jp     


# using str split to get unnest the column, 
#then we do stack, and str split again , then set the first column to index 
# after unstack we yield the result  

推荐阅读