gpt4 book ai didi

python - 我如何以这样的方式分割 pandas 数据框,为每个分割值创建一个列

转载 作者:行者123 更新时间:2023-12-01 04:07:10 27 4
gpt4 key购买 nike

例如。

输入数据框

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

最佳答案

您可以根据 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

关于python - 我如何以这样的方式分割 pandas 数据框,为每个分割值创建一个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35410870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com