我正在尝试基于csv文件中的字符串匹配在两个新列之间拆分数据。输入文件如下所示。
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”。
ID Parts Service
10 Parts warranty Service warranty
20 Parts warranty Service warranty
30 Parts warranty Service warranty
感谢任何帮助,因为我是Pandas和python的新手,我想为我正在工作的新代码弄清楚这一点。
发布于 2018-07-29 03:22:57
IIUC
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
如果需要,可以随时重命名
.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
发布于 2018-07-29 03:53:16
也许在assign
中使用pivot
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
https://stackoverflow.com/questions/51574431
复制相似问题