[英]Trying to convert list of dictionaries to a pandas dataframe
I am trying to convert a list of dictionaries to a pandas dataframe like in the stackoverflow post here, however for whatever reason I cant get it to work.我正在尝试将字典列表转换为 pandas dataframe 就像在此处的 stackoverflow 帖子中一样,但是无论出于何种原因,我都无法使其正常工作。
Convert list of dictionaries to a pandas DataFrame 将字典列表转换为 pandas DataFrame
When I try to do it with my code below, I get a 1824 rows × 1 columns data object, which is not correct (I want 6 columns).当我尝试使用下面的代码执行此操作时,我得到一个 1824 行 × 1 列的数据 object,这是不正确的(我想要 6 列)。
Here is a snapshot of my data object (returned from response.text) which I want in my pandas DataFrame这是我想要在我的 pandas DataFrame 中的数据 object(从 response.text 返回)的快照
[
{
"base_attack": 118,
"base_defense": 111,
"base_stamina": 128,
"form": "Fall_2019",
"pokemon_id": 1,
"pokemon_name": "Bulbasaur"
},
{
"base_attack": 118,
"base_defense": 111,
"base_stamina": 128,
"form": "Normal",
"pokemon_id": 1,
"pokemon_name": "Bulbasaur"
},
]
Here is my code (api key is public and used in examples):这是我的代码(api 密钥是公开的并在示例中使用):
import requests
url = "https://pokemon-go1.p.rapidapi.com/pokemon_stats.json"
headers = {
'x-rapidapi-key': "4a84fad910msha335a71778de51cp1a79d6jsnafac3cffa115",
'x-rapidapi-host': "pokemon-go1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
df = pd.DataFrame(response)
df
I have also tried these 2 approached:我也尝试过这两种方法:
df = pd.DataFrame.from_dict({k: v for d in response.text for k, v in d.items()},
orient='index',
columns=['pokemon_name', 'form', 'base_attack', 'base_defense',
'base_stamina']).rename_axis('pokemon_id').reset_index()
df = pd.DataFrame(response.text, columns=['base_attack', 'base_defense', 'base_stamina',
'form', 'pokemon_id', 'pokemon_name'])
Your response.text
is a string, not a dictionary as Pandas expects.您的
response.text
是一个字符串,而不是 Pandas 期望的字典。 You should use response.json()
if that's available.如果可用,您应该使用
response.json()
。
df = pd.DataFrame(response.json(), columns=['base_attack', 'base_defense', 'base_stamina',
'form', 'pokemon_id', 'pokemon_name'])
Alternatively, you can convert response.text
to a dictionary using json.loads
或者,您可以使用
json.loads
将response.text
转换为字典
The problem is that in df = pd.DataFrame(response)
response is not the right type of object you need as an argument.问题是在
df = pd.DataFrame(response)
响应不是您需要作为参数的 object 的正确类型。 You need to give as argument a list of Dictionaries.您需要提供一个字典列表作为参数。 You can parse the
response.text
您可以解析
response.text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.