user3447653
user3447653

Reputation: 4158

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.

Upvotes: 4

Views: 3216

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522244

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]

Upvotes: 10

Related Questions