我正在尝试获取变量的一些结果并将它们插入到pandas Dataframe中。我从Google的Merchant API获取了一些数据,我想将它们写入pandas DataFrame。 最初我正在执行对API的调用,然后使用 while ... continue 重复循环并获取下一页的结果。
MultipartFormDataContent
但是在我的输出DataFrame中,由于某种原因我只得到一行..
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import pandas as pd
def get_products(merchant_id):
request = service.products().list(merchantId=merchant_id,
maxResults=250)
while request is not None:
result = request.execute()
for product in result['resources']:
product_id = product['id']
availability = product['availability']
category = product['productType'].split('>')
category = category[0]
return product_id,availability,category
request = service.products().list_next(request, result)
continue
if __name__ == '__main__':
result = get_products('yyyy')
print result
data = {'product_id': result[0], 'availability': result[1], 'category': result[2]}
products_df = pd.DataFrame(data,index=[0])
print products_df
当我在定义的函数中测试时,我有数千行。
你认为我的逻辑有什么不对吗?
答案 0 :(得分:1)
删除所有其他语句并保留重要位:
def get_products(merchant_id):
while request is not None:
for product in result['resources']:
return product_id,availability,category # The first product will be returned by the function
continue # essentially a NOP
您遍历请求并返回找到的第一个产品。您需要聚合结果,然后返回该聚合:
def get_products(merchant_id):
result = []
while request is not None:
for product in result['resources']:
result.append((product_id,availability,category))
return result
将返回每个产品的元组列表...但请注意,您的data = {}
将无法使用此格式。