python – Pandas列重新格式化

python – Pandas列重新格式化,第1张

概述有没有快速实现以下输出的方法? 输入: Code Items123 eq-hk456 ca-eu; tp-lbe789 ca-us321 go-ch654 ca-au; go-au987 go-jp147 co-ml; go-ml258 ca-us369 ca-us; ca-my741 ca-us852 ca-eu963 ca-ml; co-ml; go-ml 输出: Co 有没有快速实现以下输出的方法?

输入:

Code Items123 eq-hk456 ca-eu; tp-lbe789 ca-us321 go-ch654 ca-au; go-au987 go-jp147 co-ml; go-ml258 ca-us369 ca-us; ca-my741 ca-us852 ca-eu963 ca-ml; co-ml; go-ml

输出:

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

我再次遇到循环和一个非常难看的代码,使其工作.如果有一种优雅的方式来实现这一点?

谢谢!

解决方法
import pandas as pddf = pd.DataFrame([    ('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',('369','ca-us; ca-my'),('741',('852','ca-eu'),('963','ca-ml; co-ml; go-ml')],columns=['Code','Items'])# Get item type List from each row,sum (concatenate) the Lists and convert# to a set to remove duplicates item_types = set(df['Items'].str.findall('(\w+)-').sum())print(item_types)# {'ca','co','eq','go','tp'}# Generate a column for each item typedf1 = pd.DataFrame(df['Code'])for t in item_types:    df1[t] = df['Items'].str.findall('%s-(\w+)' % t).apply(lambda x: ''.join(x))print(df1)#   Code    ca   tp  eq  co  go#0   123             hk        #1   456    eu  lbe            #2   789    us                 #3   321                     ch#4   654    au               au#5   987                     jp#6   147                 ml  ml#7   258    us                 #8   369  usmy                 #9   741    us                 #10  852    eu                 #11  963    ml           ml  ml
总结

以上是内存溢出为你收集整理的python – Pandas列重新格式化全部内容,希望文章能够帮你解决python – Pandas列重新格式化所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1207155.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存