遍历数据框行

时间:2019-08-22 14:34:34

标签: python pandas row

我想将数据推送到工作表。 当我打印代码时,它可以工作,但是在我的工作表上,它仅打印列表中的最后一个元素。

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

您可以将ID保存在列表id_s中,最后将其复制到DataFrame的列中。 它会起作用,因为您无需重写列。

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))
id_s=[]
for item in data["resultsPage"]["results"]["Entry"]:
    id = item["event"]["id"]
    print(id)
    id_s.append(id)
df['id_string'] = id_s