首页 > 解决方案 > 在python中根据字符串值创建单独的列

问题描述

我很新,但我正在使用如下所示的数据框:

ID       Tag  
123      Asset Class > Equity  
123      Inquiry Type > Demonstration
123      Inquiry Topic > Holdings  
456      Asset Class > Fixed Income  
456      Inquiry Type > BF   
456      Inquiry Topic > VaR 

我想要做的是将其更改为如下所示的数据框:

ID       Asset Type      Inquiry Type      Inquiry Topic  
123      Equity          Demonstration     Holdings
456      Fixed Income    Bf                VaR 

对不起,如果这很简单;但是,我对这种操作有疑问。我试过 .melt 但这似乎并没有完成我想要完成的事情。

标签: pandasdataframe

解决方案


通过索引使用split和选择拆分列表:pivot

s = df['Tag'].str.split(' > ')
df = (pd.pivot(index=df['ID'], columns=s.str[0], values=s.str[1])
       .reset_index()
       .rename_axis(None, 1))
print (df)
    ID   Asset Class Inquiry Topic   Inquiry Type
0  123        Equity      Holdings  Demonstration
1  456  Fixed Income           VaR             BF

推荐阅读