How to flatten a pandas dataframe with some columns as json?

后端 未结 4 911
日久生厌
日久生厌 2020-12-04 18:32

I have a dataframe df that loads data from a database. Most of the columns are json strings while some are even list of jsons. For example:

id           


        
4条回答
  •  半阙折子戏
    2020-12-04 18:53

    create a custom function to flatten columnB then use pd.concat

    def flatten(js):
        return pd.DataFrame(js).set_index('pos').squeeze()
    
    pd.concat([df.drop(['columnA', 'columnB'], axis=1),
               df.columnA.apply(pd.Series),
               df.columnB.apply(flatten)], axis=1)
    

提交回复
热议问题