Splitting dictionary/list inside a Pandas Column into Separate Columns

后端 未结 12 1320
南方客
南方客 2020-11-22 02:50

I have data saved in a postgreSQL database. I am querying this data using Python2.7 and turning it into a Pandas DataFrame. However, the last column of this dat

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 03:41

    Try this: The data returned from SQL has to converted into a Dict. or could it be "Pollutant Levels" is now Pollutants'

       StationID                   Pollutants
    0       8809  {"a":"46","b":"3","c":"12"}
    1       8810   {"a":"36","b":"5","c":"8"}
    2       8811            {"b":"2","c":"7"}
    3       8812                   {"c":"11"}
    4       8813          {"a":"82","c":"15"}
    
    
    df2["Pollutants"] = df2["Pollutants"].apply(lambda x : dict(eval(x)) )
    df3 = df2["Pollutants"].apply(pd.Series )
    
        a    b   c
    0   46    3  12
    1   36    5   8
    2  NaN    2   7
    3  NaN  NaN  11
    4   82  NaN  15
    
    
    result = pd.concat([df, df3], axis=1).drop('Pollutants', axis=1)
    result
    
       StationID    a    b   c
    0       8809   46    3  12
    1       8810   36    5   8
    2       8811  NaN    2   7
    3       8812  NaN  NaN  11
    4       8813   82  NaN  15
    

提交回复
热议问题