根据python中的字符串值创建单独的列

时间:2018-12-06 10:15:48

标签: pandas dataframe

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

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,但这似乎无法完成我要完成的工作。

1 个答案:

答案 0 :(得分:1)

splitpivot一起使用,并通过建立索引选择拆分列表:

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
相关问题