例如。
输入数据框
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
答案 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