通过lin添加到数据帧行

2024-04-19 23:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个数据帧,我需要逐行添加到它。我用

df = pd.DataFrame(columns=('date', 'daily_high', 'daily_low'))

然后我从API读取数据,所以我运行

for api in api_list:
    with urllib.request.urlopen(api) as url:
        data = json.loads(url.read().decode())

我需要把不同的属性从data放到数据帧中。你知道吗

我试着把

df = df.append({'date':datetime.fromtimestamp(data["currently"]["time"]).strftime("20%y%m%d"), 'daily_high' : data["daily"]["data"][0]["temperatureHigh"], 'daily_low': data["daily"]["data"][0]["temperatureLow"]},ignore_index=True)

在for循环中,但这需要很长时间,我不确定这是否是一个好的做法。有没有更好的办法?也许我可以创建三个独立的系列并将它们连接在一起?你知道吗


Tags: columns数据apiurldataframedffordata
1条回答
网友
1楼 · 发布于 2024-04-19 23:38:26

^{}对于迭代方法是低效的。你知道吗

根据文件:

Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.

如前所述,连接结果将更加有效,但在您的情况下,使用^{}将更加方便。你知道吗

另外,我将使用^{}库来请求url。你知道吗

import requests

d = {}.fromkeys(('date', 'daily_high', 'daily_low'), [])
for api_url in api_list:
    data = requests.get(api_url).json()
    d['date'].append(datetime.fromtimestamp(data["currently"]["time"]).strftime("20%y%m%d"))
    d['daily_high'].append(data["daily"]["data"][0]["temperatureHigh"])
    d['daily_low'].append(data["daily"]["data"][0]["temperatureLow"])
df = pd.DataFrame.from_dict(d)

相关问题 更多 >