Home > Software design >  Extract second character from string in Python
Extract second character from string in Python

Time:01-14

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

CodePudding user response:

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
  •  Tags:  
  • Related