如何用Python将API创建客户的响应结果存入Pandas DataFrame
问题描述
我需要在账单系统中创建新客户,获取包含新客户ID和创建时间戳的API响应,并将所有响应数据存入Pandas DataFrame以便后续处理。以下是我目前的代码,但不清楚如何将多字段的响应追加到DataFrame中:
new_customers = pd.DataFrame() for customer,r in sh2_ws_df.iterrows(): cb.Customer.create({ "first_name": r['Billing First Name'], "last_name": r['Billing Last Name'], "email": r['Billing Email'], "phone": r['Billing Phone'], "company": r['Account Name'], "auto_collection": "on", "net_term_days": 0, "allow_direct_debit": 'true', "taxability": "taxable", "locale": "en", "cf_referral_partner": r['cb_referral_partner'], "cf_business_type": r['cf_business_type'], "billing_address" : { "first_name" : r['Billing First Name'], "last_name" : r['Billing Last Name'], "email": r['Billing Email'], "company": r['Account Name'], "phone": r['Billing Phone'], "line1" : r['Billing Address 1'], "line2": r['Billing Address 2'], "city" : r['Billing City'], "state" : r['Billing State'], "zip" : r['Billing Zip'], "country" : r['Billing Country'] } } new_customers.append() )
解决方案
你的代码存在几个核心问题:未捕获API响应数据、append()方法使用错误、语法括号不匹配。下面是修正后的高效实现方式:
推荐实现:先收集响应列表再转DataFrame
import pandas as pd # 初始化空列表存储每个客户的API响应数据 customer_responses = [] # 遍历源数据创建客户 for _, r in sh2_ws_df.iterrows(): # 调用API创建客户并捕获返回的响应对象 response = cb.Customer.create({ "first_name": r['Billing First Name'], "last_name": r['Billing Last Name'], "email": r['Billing Email'], "phone": r['Billing Phone'], "company": r['Account Name'], "auto_collection": "on", "net_term_days": 0, "allow_direct_debit": 'true', "taxability": "taxable", "locale": "en", "cf_referral_partner": r['cb_referral_partner'], "cf_business_type": r['cf_business_type'], "billing_address" : { "first_name" : r['Billing First Name'], "last_name" : r['Billing Last Name'], "email": r['Billing Email'], "company": r['Account Name'], "phone": r['Billing Phone'], "line1" : r['Billing Address 1'], "line2": r['Billing Address 2'], "city" : r['Billing City'], "state" : r['Billing State'], "zip" : r['Billing Zip'], "country" : r['Billing Country'] } }) # 将响应对象转为字典(多数API返回的对象支持to_dict()方法,若直接返回字典可跳过此步) customer_data = response.to_dict() if hasattr(response, 'to_dict') else dict(response) # 将单条客户数据追加到列表 customer_responses.append(customer_data) # 一次性将列表转为DataFrame,效率远高于循环追加 new_customers = pd.DataFrame(customer_responses) # 若需要展开嵌套的billing_address字段为平级列,使用json_normalize # new_customers = pd.json_normalize(customer_responses)
关键说明
- 捕获API响应:必须将
cb.Customer.create()的返回值赋值给变量,才能获取到新客户ID、创建时间戳等核心数据。 - 避免循环操作DataFrame:循环中使用
append()(已被Pandas弃用)会频繁生成新DataFrame,性能极低,先收集列表再批量转换是最优方案。 - 处理嵌套字段:如果API响应包含
billing_address这类嵌套结构,pd.json_normalize()可以将嵌套字段展开为平级列,方便后续分析处理。 - 语法修正:原代码中
cb.Customer.create()的大括号未闭合,修正后确保代码语法合法。
内容的提问来源于stack exchange,提问作者Mike P
相关产品推荐
相关产品推荐

