Search code examples
arrayspandasdataframescalar

Convert one dimensional arrays in a pandas dataframe to numbers


Values of a pandas dataframe contain one dimensional arrays and i would like to convert into floats without the "[]" . Tried this but does not work . How can [0.5142399408894116] be converted to 0.5142399408894116

dfPredictions = pd.DataFrame(data = dff, dtype='float')

Solution

  • Use the index operator [] on the array:

    [0.5142399408894116][0]
        = 0.5142399408894116
    

    If you need to apply this to a dataframe row, use the explode method:

    df = pd.DataFrame({'col': [[0.5142399408894116], [0.1423994088941165], [0.4239940889411651]]})
    
    df
        col
    0   [0.5142399408894116]
    1   [0.1423994088941165]
    2   [0.4239940889411651]
    
    df.explode('col')
    
        col
    0   0.51424
    1   0.142399
    2   0.423994