在pandas数据帧中将列拆分为多个具有特定名称的列

时间:2018-01-11 12:29:19

标签: python pandas dataframe

我有以下数据框:

pri    sec
TOM    AB,CD,EF
JACK   XY,YZ
HARRY  FG
NICK   KY,NY,SD,EF,FR

我需要跟随列名的输出如下(基于'sec'列中存在多少个分隔的字段):

pri    sec             sec0  sec1  sec2  sec3 sec4
TOM    AB,CD,EF        AB    CD    EF    NaN  NaN
JACK   XY,YZ           XY    YZ    NaN   NaN  NaN
HARRY  FG              FG    NaN   NaN   NaN  NaN
NICK   KY,NY,SD,EF,FR  KY    NY    SD    EF   ER

我能得到任何建议吗?

2 个答案:

答案 0 :(得分:10)

使用join + split + add_prefix

df = df.join(df['sec'].str.split(',', expand=True).add_prefix('sec'))
print (df)
     pri             sec sec0  sec1  sec2  sec3  sec4
0    TOM        AB,CD,EF   AB    CD    EF  None  None
1   JACK           XY,YZ   XY    YZ  None  None  None
2  HARRY              FG   FG  None  None  None  None
3   NICK  KY,NY,SD,EF,FR   KY    NY    SD    EF    FR

如果需要NaN添加fillna

df = df.join(df['sec'].str.split(',', expand=True).add_prefix('sec').fillna(np.nan))
print (df)
     pri             sec sec0 sec1 sec2 sec3 sec4
0    TOM        AB,CD,EF   AB   CD   EF  NaN  NaN
1   JACK           XY,YZ   XY   YZ  NaN  NaN  NaN
2  HARRY              FG   FG  NaN  NaN  NaN  NaN
3   NICK  KY,NY,SD,EF,FR   KY   NY   SD   EF   FR

答案 1 :(得分:1)

尝试以下代码(解释为注释)。它在“sec”列中找到项目的最大长度,并相应地创建名称:

maxlen = max(list(map(lambda x: len(x.split(",")) ,df.sec))) # find max length in 'sec' column
cols = ["sec"+str(x)   for x in range(maxlen)]      # create new column names 
datalist = list(map(lambda x: x.split(","), df.sec)) # create list from entries in "sec" 
newdf = pd.DataFrame(data=datalist, columns=cols)   # create dataframe of new columns
newdf = pd.concat([df, newdf], axis=1)              # add it to original dataframe
print(newdf)

输出:

     pri             sec sec0  sec1  sec2  sec3  sec4
0    TOM        AB,CD,EF   AB    CD    EF  None  None
1   JACK           XY,YZ   XY    YZ  None  None  None
2  HARRY              FG   FG  None  None  None  None
3   NICK  KY,NY,SD,EF,FR   KY    NY    SD    EF    FR