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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45019319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:58:15  来源:igfitidea点击:

Pandas: Split a string and then create a new column?

pythonpandas

提问by Jun Jang

enter image description here

在此处输入图片说明

Let's say you have Col1.

假设您有 Col1。

How do you create the new column 'Col2' after you split the string values in Col1 until you see _?

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

回答by Scott Boston

Edit to handle strings without '_':

编辑以处理没有“_”的字符串:

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

OR as COLDSPEED suggests in comments:

或者像 COLDSPEED 在评论中建议的那样:

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

You can use the .str access with indexing:

您可以将 .str 访问与索引一起使用:

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

Example:

例子:

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

Output:

输出:

          Col1    Col2
0    Name_John    John
1     Name_Jay     Jay
2  Name_Sherry  Sherry

回答by YOBEN_S

I think this will work . If...elselogic here is for your additional requested, when do not have '_'keep the original

我认为这会奏效。If...else这里的逻辑是为了您的额外要求,当没有'_'保留原件时

   df['Col2']= df['Col1'].apply(lambda x: x.split('_')[1] if x.find('_')!=-1 else x )

回答by hui chen

You can simply use str.split()method with expand=Trueargument.

您可以简单地使用str.split()expand=True参数的方法。

For example:

例如:

ncaa[['Win', 'Lose']] = ncaa['Record'].str.split('-', expand=True)