【发布时间】:2019-08-22 14:34:34
【问题描述】:
我想将数据推送到工作表。 当我打印我的代码时它正在工作,但在我的工作表上它只打印我列表的最后一个元素。
这是我的代码:
import json
from urllib.request import urlopen
import pygsheets
import pandas as pd
with urlopen("myapiurl") as response: source = response.read()
data = json.loads(source)
#authorization
gc = pygsheets.authorize(service_file='myjsonfile')
#open the google spreadsheet
sh = gc.open('Test')
#select the first sheet
wks = sh[0]
# Create empty dataframe
df = pd.DataFrame()
#update the first sheet with df, starting at cell B2.
wks.set_dataframe(df,(1,1))
for item in data["resultsPage"]["results"]["Entry"]:
id = item["event"]["id"]
print(id)
df['id_string'] = id
【问题讨论】:
-
你的循环每次都会覆盖
df['id_string'],所以你只会得到最后一个id。 -
@mnlgr 从我的脑海中消失,您应该将其附加到列表中,然后将其添加到数据框
-
在 for 循环外声明一个空数组,然后用空数组的名称更改最后一行,并调用 append 函数并在每个循环中将 id 附加到它。然后最后将您声明的数组分配给 df["id_string"]