我正在尝试根据csv文件中的字符串匹配在两个新列之间拆分数据。输入文件如下所示。
ID Service Type
10 Parts warranty
20 Service warranty
30 Parts warranty
10 Service warranty
30 Service warranty
20 Parts warranty
如果“服务类型”列数据与“零件保修”相匹配,则应移至新的“零件”列;如果“服务类型”列数据与“服务保修”相匹配,则应移至新的“服务”列,并删除原始的“服务”列输入'。
ID Parts Service
10 Parts warranty Service warranty
20 Parts warranty Service warranty
30 Parts warranty Service warranty
感谢大家的帮助,因为我是Pandas和python的新手,并希望为我正在开发的新代码弄清楚这一点。
答案 0 :(得分:0)
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
答案 1 :(得分:0)
也许将pivot
与assign
一起使用
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