Let's say you have Col1.
How do you create the new column 'Col2' after you split the string values in Col1 until you see _?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With