简体   繁体   中英

Split dataframe column containing list inside a string to two columns

I have a df where one column, 'vals' contains a list inside a string. I want to convert this into two columns 'val1' and 'vals2. I have tried to split and strip the string but can't find an implementation to do this for every row in the df.

    vals
'[12.1, 15.0]'

val1  val2
12.1  15.0

Use strip with split and casting to floats if necessary, last add prefix by add_prefix :

df = pd.DataFrame({'vals':["'[12.1, 15.0]'","'[12.1, 15.0]'"]})

df = (df['vals'].str.strip("'[]")
               .str.split(', ', expand=True)
               .astype(float)
               .add_prefix('val'))

If no missing values and performance is important:

df =  pd.DataFrame([x.strip("'[]").split(', ') for x in df['vals']], 
                    columns = ['val1', 'val2']).astype(float)

Here we employ ast.literal_eval -

import ast
df = pd.DataFrame({'A':['[12.1, 15.0]','[12.4, 11.1]']})
df['val1']=df['A'].apply(lambda x:ast.literal_eval(x)[0])
df['val2']=df['A'].apply(lambda x:ast.literal_eval(x)[1])
df    
                A  val1  val2
  0  [12.1, 15.0]  12.1  15.0
  1  [12.4, 11.1]  12.4  11.1

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