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
Pandas: Split a string and then create a new column?
提问by Jun Jang
回答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...else
logic 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=True
argument.
您可以简单地使用str.split()
带expand=True
参数的方法。
For example:
例如:
ncaa[['Win', 'Lose']] = ncaa['Record'].str.split('-', expand=True)