1

I have a dataframe with a column that holds certain values where I would like to extract the second string after the hyphen and keep the original.

Data

   type            stat
   SSS-AA-11111    y
   FFF-BB-22222    y

Desired

type            type1 stat
SSS-AA-11111    AA    y
FFF-BB-22222    BB    y

Doing

  df[['type', 'type1']] = df['type'].str.split('-', 1, expand=True)`

I get this error:

ValueError: Columns must be same length as key

I am still researching. Any suggestion is appreciated

1 Answer 1

2

Use str.split and keep the second element with str[1]:

df['type1'] = df['type'].str.split('-').str[1]
print(df)

# Output
           type stat type1
0  SSS-AA-11111    y    AA
1  FFF-BB-22222    y    BB
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.