0

I want to push data to a sheet. When i'm printing my code it is working, but on my sheet it prints only the last element of my list.

Here is my code :

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
3
  • 1
    your loop will overwrite df['id_string'] each time, so you'll only end up with the last id. Commented Aug 22, 2019 at 14:37
  • @mnlgr off the top of my head, you should append it to a list and then add it to the dataframe Commented Aug 22, 2019 at 14:41
  • declare an empty array out outside the for loop and then change the last line with the name of the empty array and call the append function and append the id to it on every loop. and then at the end assign the array you declared to the df["id_string"] Commented Aug 22, 2019 at 14:42

1 Answer 1

1

You can save ids in a list id_s an finally copy it in the colum of DataFrame. it will work because you don't rewrite the colum.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.