将字典转换为pandas数据框架

mzaanser  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(97)

我有一本字典如下:

{'result': '{"maid":{"0":"0365206d-e97d-4ab0-aa63-64091e66a1a4","1":"0955bbcc-3a83-4c64-8170-f5deb799a5ba","2":"0570ba29-1ee8-4bc6-a12c-c2b706d805c8"},"category":{"0":"EventHall","1":"SuperMarket","2":"Bank"},"geo_behavior":{"0":null,"1":null,"2":null},"polygonid":{"0":2332,"1":2332,"2":2332},"places":{"0":"Shri Sai Dj","1":"D Mart","2":"Bank of Baroda"},"age":{"0":38.0,"1":18.0,"2":37.0},"gender":{"0":0.0,"1":0.0,"2":0.0},"mobile":{"0":null,"1":null,"2":null},"make":{"0":"oppo","1":"vivo","2":"oneplus"},"deviceprice":{"0":160.0,"1":190.0,"2":392.0},"weight":{"0":2.5684166749,"1":2.0,"2":2.0},"__index_level_0__":{"0":0,"1":1,"2":2}}'}

字符串
我试图将这个字典解析为一个数据框架。我尝试了以下方法:

l=k.get("result")
m=json.loads(l)
maid=m.get('maid')
cate=m.get('category')
geobh=m.get('geo_behavior')
pid=m.get('polygonid')
places=m.get('places')
age=m.get('age')
gender=m.get('gender')
mobile=m.get('mobile')
make=m.get('make')
deviceprice=m.get('deviceprice')
weight=m.get('weight')


这给了我单独的字典合并以形成数据框架。我也试过

pd.json_normalize
pd.DataFrame.from_records(


但帮不上忙我想知道是否有更简单的方法将result转换为字典。

oknwwptz

oknwwptz1#

你可以使用pandas read_json读取result节点并将其加载到df中,如下所示:

import pandas as pd
json_ = {} # your json/dictionary 
df = pd.read_json(json_['result'])
print(df.head)

字符串
产出:

maid     category  geo_behavior  polygonid              places  age  gender  mobile     make  deviceprice    weight     __index_level_0__  
0  0365206d-e97d-4ab0-aa63-64091e66a1a4    EventHall           NaN       2332         Shri Sai Dj   38       0     NaN     oppo          160  2.568417                     0  
1  0955bbcc-3a83-4c64-8170-f5deb799a5ba  SuperMarket           NaN       2332              D Mart   18       0     NaN     vivo          190  2.000000                     1  
2  0570ba29-1ee8-4bc6-a12c-c2b706d805c8         Bank           NaN       2332      Bank of Baroda   37       0     NaN  oneplus          392  2.000000                     2  

[3 rows x 12 columns]

相关问题