gpt4 book ai didi

python - 为每一行创建的 Pandas DataFrame

转载 作者:行者123 更新时间:2023-11-28 18:05:53 26 4
gpt4 key购买 nike

我正在尝试将 JSON 格式的数据从 API 传递到 Pandas DataFrame。我无法让 pandas.read_json 处理 API 数据,所以我确定这不是最好的解决方案,但我目前有 for loop 运行 JSON 以提取我想要的值。

这是我的:

import json
import urllib.request
import pandas as pd

r = urllib.request.urlopen("https://graph.facebook.com/v3.1/{page-id}/insights?access_token={access-token}&pretty=0&metric=page_impressions%2cpage_engaged_users%2cpage_fans%2cpage_video_views%2cpage_posts_impressions").read()

output = json.loads(r)

for item in output['data']:
name = item['name']
period = item['period']
value = item['values'][0]['value']

df = [{'Name': name, 'Period': period, 'Value': value}]

df = pd.DataFrame(df)

print(df)

这里是 API 中 JSON 的摘录:

    {
"data": [
{
"name": "page_video_views",
"period": "day",
"values": [
{
"value": 634,
"end_time": "2018-11-23T08:00:00+0000"
},
{
"value": 465,
"end_time": "2018-11-24T08:00:00+0000"
}
],
"title": "Daily Total Video Views",
"description": "Daily: Total number of times videos have been viewed for more than 3 seconds. (Total Count)",
"id": "{page-id}/insights/page_video_views/day"
},

我现在面临的问题是因为 For 循环(我相信),每一行数据都被插入到它自己的 DataFrame 中,如下所示:

               Name Period  Value
0 page_video_views day 465
Name Period Value
0 page_video_views week 3257
Name Period Value
0 page_video_views days_28 9987
Name Period Value
0 page_impressions day 1402

我怎样才能像这样轻松地将它们全部传递到同一个 DataFrame 中?

               Name Period  Value
0 page_video_views day 465
1 page_video_views week 3257
2 page_video_views days_28 9987
3 page_impressions day 1402

同样,我知道这很可能不是最佳解决方案,因此非常欢迎任何关于如何改进任何方面的建议。

最佳答案

您可以创建字典列表并传递给 DataFrame 构造函数:

L = []
for item in output['data']:
name = item['name']
period = item['period']
value = item['values'][0]['value']

L.append({'Name': name, 'Period': period, 'Value': value})

df = pd.DataFrame(L)

或者使用列表理解:

L = [({'Name': item['name'], 'Period': item['period'], 'Value': item['values'][0]['value']}) 
for item in output['data']]

df = pd.DataFrame(L)
print (df)
Name Period Value
0 page_video_views day 634

测试样本:

output = {
"data": [
{
"name": "page_video_views",
"period": "day",
"values": [
{
"value": 634,
"end_time": "2018-11-23T08:00:00+0000"
},
{
"value": 465,
"end_time": "2018-11-24T08:00:00+0000"
}
],
"title": "Daily Total Video Views",
"description": "Daily: Total number of times videos have been viewed for more than 3 seconds. (Total Count)",
"id": "{page-id}/insights/page_video_views/day"
}]}

关于python - 为每一行创建的 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53512489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com