首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python中基于字符串匹配将原始列中的数据拆分成两个新列?

在Python中基于字符串匹配将原始列中的数据拆分成两个新列?
EN

Stack Overflow用户
提问于 2018-07-29 03:11:04
回答 2查看 56关注 0票数 1

我正在尝试基于csv文件中的字符串匹配在两个新列之间拆分数据。输入文件如下所示。

代码语言:javascript
复制
ID  Service Type
10  Parts warranty
20  Service warranty
30  Parts warranty
10  Service warranty
30  Service warranty
20  Parts warranty

如果“Service Type”列数据与部件保修匹配,则应移至新列“Parts”;如果“Service Type”列数据与服务保修匹配,则应移至新“Service”列,并删除原始列“Service Type”。

代码语言:javascript
复制
ID  Parts           Service
10  Parts warranty  Service warranty
20  Parts warranty  Service warranty
30  Parts warranty  Service warranty

感谢任何帮助,因为我是Pandas和python的新手,我想为我正在工作的新代码弄清楚这一点。

EN

回答 2

Stack Overflow用户

发布于 2018-07-29 03:22:57

IIUC

代码语言:javascript
复制
df.pivot_table(values='Service Type', columns='Service Type' , index='ID',  aggfunc=lambda k: k.name[-1])

Service Type    Parts warranty  Service warranty
ID      
10              Parts warranty  Service warranty
20              Parts warranty  Service warranty
30              Parts warranty  Service warranty

如果需要,可以随时重命名

代码语言:javascript
复制
.rename(columns={'Parts warranty': 'Parts', 
                 'Service warranty': 'Service'})


Service Type    Parts           Service
ID      
10              Parts warranty  Service warranty
20              Parts warranty  Service warranty
30              Parts warranty  Service warranty
票数 0
EN

Stack Overflow用户

发布于 2018-07-29 03:53:16

也许在assign中使用pivot

代码语言:javascript
复制
df.assign(Type=df['Service Type'].str.split(' ').str[0]).pivot('ID','Type','Service Type')
Out[575]: 
Type           Parts           Service
ID                                    
10    Parts warranty  Service warranty
20    Parts warranty  Service warranty
30    Parts warranty  Service warranty
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51574431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档