Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas convert list to float

Tags:

python

pandas

How could I convert column b and column c to float and also expend column b to two columns.

Example dataframe:

    a                              b             c
0  36   [-212828.804308, 100000067.554]  [-3079773936.0]
1  39  [-136.358761948, -50000.0160325]  [1518911.64408]
2  40  [-136.358761948, -50000.0160325]  [1518911.64408]

Expected:

    a        b1                  b2             c
0  36   -212828.804308  100000067.554  -3079773936.0
1  39  -136.358761948, -50000.0160325  1518911.64408
2  40  -136.358761948, -50000.0160325  1518911.64408
like image 394
galaxyan Avatar asked Feb 05 '23 14:02

galaxyan


1 Answers

Here are two alternatives:

1) Convert the columns to a list then construct a DataFrame from scratch:

pd.concat((df['a'], pd.DataFrame(df['b'].tolist()), pd.DataFrame(df['c'].tolist())), axis=1)
Out: 
    a              0             1             0
0  36 -212828.804308  1.000001e+08 -3.079774e+09
1  39    -136.358762 -5.000002e+04  1.518912e+06
2  40    -136.358762 -5.000002e+04  1.518912e+06

Or in a loop:

pd.concat((pd.DataFrame(df[col].tolist()) for col in df), axis=1)
Out: 
    0              0             1             0
0  36 -212828.804308  1.000001e+08 -3.079774e+09
1  39    -136.358762 -5.000002e+04  1.518912e+06
2  40    -136.358762 -5.000002e+04  1.518912e+06

2) Apply pd.Series to each column (possibly slower):

pd.concat((df[col].apply(pd.Series) for col in df), axis=1)
Out: 
    0              0             1             0
0  36 -212828.804308  1.000001e+08 -3.079774e+09
1  39    -136.358762 -5.000002e+04  1.518912e+06
2  40    -136.358762 -5.000002e+04  1.518912e+06
like image 55
ayhan Avatar answered Feb 16 '23 01:02

ayhan