python - 熊猫列重新格式化
问题描述
有什么快速的方法可以实现以下输出吗?
输入:
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
我再次陷入循环和一个非常丑陋的代码使其工作。如果有一种优雅的方式来实现这一点?
谢谢!
解决方案
这有点复杂
(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
推荐阅读
- powershell - 使用查找 csv 文件重命名
- java - 如何配置 ldaptive 以使用连接池 (jaas)
- python - Pandas:使用 np.where() 删除值小于今天的行?
- arrays - 声明具有特定类型但任意维数的数组
- bash - Crontab:在无限循环中运行的计划作业卡住了
- python - 如何在 Python 3 中腌制日期时间以供 Python 2 读取
- python - 查找字符串中字符的位置
- javascript - 让模态显示在调用的 vue 方法中
- node.js - 在 Loopback 3 中刷新 AccessToken
- visual-studio - visual studio 2019 打开解决方案文件不兼容