将Pandas数据框转换为JSON

时间:2019-09-27 06:57:27

标签: python json pandas dataframe

我想将Pandas数据框转换为具有某些json结构的json或字符串。

我的数据框如下:

import pandas as pd
df = pd.DataFrame([['country1','AdUnit1','floor_price1','feature1',1111],
                   ['country1','AdUnit1','floor_price1','feature2',1112],
                   ['country1','AdUnit1','floor_price2','feature1',1121],
                   ['country1','AdUnit2','floor_price1','feature1',1211],
                   ['country1','AdUnit2','floor_price2','feature1',1221],
                   ['country2','AdUnit1','floor_price1','feature1',2111],
                   ['country2','AdUnit1','floor_price1','feature2',2112]],
                  columns=['col 1', 'col 2','col3','col 4','col 5'])

Given dataframe

我想将其转换为json,如下所示:

{ 
   "country1":{ 
      "AdUnit1":{ 
         "floor_price1":{ 
            "feature1":1111,
            "feature2":1112
         },
         "floor_price2":{ 
            "feature1":1121
         }
      },
      "AdUnit2":{ 
         "floor_price1":{ 
            "feature1":1211
         },
         "floor_price2":{ 
            "feature1":1221
         }
      }
   },
   "country2":{ 
      "AdUnit1":{ 
         "floor_price1":{ 
            "feature1":2111,
            "feature2":2112
         }
      }
   }
}

我尝试将to_json与 orient 选项的多个选项一起使用,但没有成功。

请。帮助我解决它。谢谢。

0 个答案:

没有答案