简体   繁体   中英

Extract second character from string in Python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM