Reputation: 37
Fetching data from API with for loop, but only last row is showing. If i put print
statement instead of d=
, I get all records for some reason. How to populate a Dataframe
with all values?
I tried with for loop and with append but keep getting wrong results
for x in elements:
url = "https://my/api/v2/item/" + str(x[number"]) + "/"
get_data = requests.get(url)
get_data_json = get_data.json()
d = {'id': [x["enumber"]],
'name': [x["value1"]["name"]],
'adress': [value2["adress"]],
'stats': [get_data_json["stats"][5]["rating"]]
}
df = pd.DataFrame(data=d)
df.head()
Result:
id name order adress rating
Only last row is showing, probably because it's overwriting until it comes to last element. Should I put another for loop somewhere or there is some obvious solution that I cannot see?
Upvotes: 0
Views: 1265
Reputation: 4341
Put all your data into a list of dictionaries, then convert to a dataframe at the very end
At the top of your code write:
all_data = []
Then in your loop, after d = {...}, write
all_data.append(d)
Finally at the end (after the loop has finished)
df = pd.DataFrame(all_data)
Upvotes: 3