簡體   English   中英

ValueError:DataFrame 構造函數未正確調用! 當將列表中的字典覆蓋到 pandas dataframe

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM