gpt4 book ai didi

python - Pandas:拆分字符串然后创建一个新列?

转载 作者:行者123 更新时间:2023-12-03 03:20:39 24 4
gpt4 key购买 nike

enter image description here

假设您有 Col1。

拆分 Col1 中的字符串值直到看到 _ 后,如何创建新列“Col2”?

最佳答案

编辑以处理不带“_”的字符串:

df['Col2'] = (np.where(df['Col1'].str.contains('_'),
df['Col1'].str.split('_').str[1],
df['Col1']))

或者正如 COLDPEED 在评论中建议的那样:

df['Col1'].str.split('_').str[-1]

您可以使用带有索引的 .str 访问:

df['Col2'] = df['Col1'].str.split('_').str[1]

示例:

df = pd.DataFrame({'Col1':['Name_John','Name_Jay','Name_Sherry']})
df['Col2'] = df['Col1'].str.split('_').str[1]

输出:

          Col1    Col2
0 Name_John John
1 Name_Jay Jay
2 Name_Sherry Sherry

关于python - Pandas:拆分字符串然后创建一个新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45019319/

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