gpt4 book ai didi

python - 拆分 Pandas 列并将新结果附加到数据框

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:00 25 4
gpt4 key购买 nike

如何拆分 pandas 列并将新结果附加到数据框?我也希望没有空白。

我想要的输出示例:

col1
Smith, John
Smith, John

col2
Smith
Smith

col3
John
John

我一直在尝试这个,但 lambda 函数没有按照我想要的方式附加结果。

df_split = df1['col1'].apply(lambda x: pd.Series(x.split(',')))
df1['col2']= df_split.apply(lambda x: x[0])
df1['col3']= df_split.apply(lambda x: x[1])

我最终得到

col2  col3
Smith Smith
John John

最佳答案

使用Series.str.split(..., expand=True) :

df[['col2', 'col3']] = df.col1.str.split(',\s+', expand=True); df

col1 col2 col3
0 Smith, John Smith John
1 Smith, John Smith John

关于python - 拆分 Pandas 列并将新结果附加到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45359956/

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