Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get characters before the underscore

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.

like image 841
user3447653 Avatar asked Oct 18 '25 10:10

user3447653


1 Answers

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]
like image 174
Tim Biegeleisen Avatar answered Oct 21 '25 01:10

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!