【问题标题】:Loop through dataframe rows循环遍历数据框行
【发布时间】: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"]

标签: python pandas row


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2022-01-20
    • 2018-12-31
    • 2020-11-20
    • 2018-10-16
    相关资源
    最近更新 更多