我如何以这样的方式拆分pandas数据框:对于每个拆分值,它创建一个列

时间:2016-02-15 13:39:05

标签: python pandas split dataframe

例如。

输入数据框

Name     Subjects
Ramesh   Maths,Science
Rakesh   MAths,Science,Social Studies
John     Social Science, Lietrature

输出数据框

Name     Subject1       Subject2     Subjects3
Ramesh   Maths          Science      NaN
Rakesh   MAths          Science      Social Studies
John     Social Science Literature   Nan

1 个答案:

答案 0 :(得分:2)

您可以从str.split的结果创建一个新的df,然后concat

In [66]:
subjects = df['Subjects'].str.split(',', expand=True)
subjects

Out[66]:
                0           1               2
0           Maths     Science            None
1           MAths     Science  Social Studies
2  Social Science  Lietrature            None

In [71]:    
subjects.columns = ['Subject ' + str(x + 1) for x in range(len(subjects.columns))]
subjects

Out[71]:
        Subject 1   Subject 2       Subject 3
0           Maths     Science            None
1           MAths     Science  Social Studies
2  Social Science  Lietrature            None

In [74]:
concatenated = pd.concat([df,subjects], axis=1)
concatenated.drop('Subjects',axis=1,inplace=True)
concatenated

Out[74]:
     Name       Subject 1   Subject 2       Subject 3
0  Ramesh           Maths     Science            None
1  Rakesh           MAths     Science  Social Studies
2    John  Social Science  Lietrature            None