python - Pandas split a column value to new column if list -


i still learning pandas , have pandas dataframe 2 columns shown below:

actual label          pred label      0                    -1      0                    -1      1           [1, 0.34496911461303364]      1                    -1 

what accomplish if value in 'pred label' list take first value in list, in case 1, , keep in column , take second value in list , put in own column 'pred score'.

it's not great idea store dataframe in initial format in first place if can avoided. here solution:

import pandas pd  df = pd.dataframe({'actual_label' : [0,0,1,1],                   'pred_label' : [-1,-1, [1, 0.34496911461303364], -1]})  def split_label(v):   if isinstance(v, list):     return pd.series(v, index = ['pred_label', 'pred_score'])   return pd.series(v, index = ['pred_label'])  new_pred = df.pred_label.apply(split_label) df_new = pd.concat([df.actual_label, new_pred], axis=1) 

the final output looks this:

   actual_label  pred_label  pred_score 0             0          -1         nan 1             0          -1         nan 2             1           1    0.344969 3             1          -1         nan 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -