I have a pandas dataframe in the below format
name
BC_new-0
BC_new-1
BC_new-2
Would like to extract whatever is below the "_" and append it to a new column
df['value'] = str(df['name']).split("_")[0]
But I get the below results
value
0 BC
0 BC
0 BC
Any suggestions on how this "0" could not be present in the output. Any leads would be appreciated.
CodePudding user response:
I might use str.extract
here:
df['value'] = df['name'].str.extract(r'^([^_] )')
As the comment above suggests, if you want to use string splitting, then use str.split
:
df['value'] = df['name'].str.split("_").str[0]