Pandas: Split a string and then create a new column?
I think this will work . If...else
logic here is for your additional requested, when do not have '_'
keep the original
df['Col2']= df['Col1'].apply(lambda x: x.split('_')[1] if x.find('_')!=-1 else x )
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:
df['Col1'].str.split('_').str[-1]
You can use the .str access with indexing:
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
You can simply use str.split()
method with expand=True
argument.
For example:
ncaa[['Win', 'Lose']] = ncaa['Record'].str.split('-', expand=True)