![](/img/trans.png)
[英]ValueError: DataFrame constructor not properly called! with pandas
[英]ValueError: DataFrame constructor not properly called! when coverting dictionaries within list to pandas dataframe
我想将字典列表转换为 pandas dataframe,但是,我得到了ValueError: DataFrame constructor not properly called!
下面是一个示例以及我如何获取数据:
import requests
import pandas as pd
# Send an HTTP GET request to the URL
response = requests.get(url)
# Decode the JSON data into a dictionary
scrapped_data = response.text
response.text
的内容是:
[{"id":123456,"date":"12-12-2022","value":37},{"id":123456,"date":"13-12-2022","value":38}]
我想将其转换为 dataframe 格式,如下所示:
ID | 日期 | 价值 |
---|---|---|
123456 | 12-12-2022 | 37 |
123456 | 13-12-2022 | 38 |
我尝试了以下方法:
df = pd.DataFrame(scrapped_data)
df = pd.DataFrame_from_dict(scrapped_data)
df = pd.DataFrame(scrapped_data, orient='columns')
都有相同的值错误。
我也试过:
df = pd.json_normalize(scrapped_data)
但得到了NotImplementedError
scrapped_data 的类型是字符串格式
感谢您的帮助,如果您有任何问题,请告诉我
如您所说, scrapped_data 是一个字符串,然后您需要将其转换为字典(例如,使用从 json 库加载的方法)。
如果 scrapped_data = '[{"id":"123456","date":"12-12-2022","value":"37"}, {"id":"123456","date":"13 -12-2022","value":"38"}]',那么你可以只做 df = pd.DataFrame(scrapped_data)。
从pandas
收到此错误的原因之一是提供str
作为数据。 我认为您的数据来自str
,如果是这样,请尝试以下操作:
import json
import pandas as pd
orignal_data='[{"id":"123456","date":"12-12-2022","value":"37"}, {"id":"123456","date":"13-12-2022","value":"38"}]'
scraped_data = json.loads(orignal_data)
df = pd.DataFrame(data=scraped_data)
df
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.