python – Pandas列重新格式化
发布时间:2020-12-15 08:19:19 所属栏目:Python 来源:互联网
导读:有没有快速实现以下输出的方法? 输入: 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 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 我再次遇到循环和一个非常难看的代码,使其工作.如果有一种优雅的方式来实现这一点? 谢谢! 解决方法import pandas as pd
df = 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 type
df1 = 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 – 有人可以解释为什么这会修复我的递归错误吗?
- 如何使用PIL(python-imaging)创建透明的gif(或png)
- python – 查找numpy数组中每行的最大值以及相同大小的另一
- python – 单元测试(烧瓶 – 静止)GET API调用时获得500内部
- 即使在运行迁移后,Django Programming错误列也不存在
- python – 将日期列和时间列合并到datetime列
- python – 从字符串列表中分离的字符串创建字典
- python – GTK标签包装在一个对话框中
- Django在内联表单管理中获取实例
- TypeError:’function’对象不可订阅 – Python
