python - 如何通过读取 csv 数据并在 API 有效负载中使用来形成正确的 JSON
问题描述
我正在使用以下代码通过从 csv 读取数据来形成 JSON
df = pd.read_csv('/testdata.csv', dtype={
"debt_type": str,
"debt_amount": int,
"interest_rate": float,
"total_monthly_payment": int,
"remaining_term,interest_payable": int})
finalList = []
finalDict = {}
grouped = df.groupby(['debt_type'])
for key, value in grouped:
dictionary = {}
j = grouped.get_group(key).reset_index(drop=True)
dictionary['debt_type'] = j.at[0, 'debt_type']
dictList = []
anotherDict = {}
for i in j.index:
anotherDict['debt_amount'] = j.at[i, 'debt_amount']
anotherDict['interest_rate'] = j.at[i, 'interest_rate']
anotherDict['total_monthly_payment'] = j.at[i, 'total_monthly_payment']
anotherDict['remaining_term'] = j.at[i, 'remaining_term']
anotherDict['interest_payable'] = j.at[i, 'interest_payable']
dictList.append(anotherDict)
dictionary['loan_info'] = dictList
finalList.append(dictionary)
finalDict = finalList
并想实现以下
{"loan_info":{"debt_amount":9000,"interest_rate":23,"total_monthly_payment":189,"remaining_term":129,"interest_payable":15356},"debt_type":"credit_card"}
但是,我得到的是下面
[{'debt_type': 'credit_card', 'loan_info': [{'debt_amount': 9000, 'interest_rate': 12.2, 'total_monthly_payment': 189, 'remaining_term': 129, 'interest_payable': 15256}]}]
任何人都可以在这里帮忙。提前致谢。
解决方案
我认为您需要使用pandas.DataFrame.to_dict()和pandas.DataFrame.to_json()。
阅读完 csv 文件后,您可以创建一个新列loan_info
,将您想要的所有字段格式化为 Python 字典:
loan_info_cols = ['debt_amount', 'interest_rate', 'total_monthly_payment', 'remaining_term', 'interest_payable']
df['loan_info'] = df[loan_info_cols].apply(lambda x: x.to_dict(), axis=1)
然后删除我们刚刚使用的列:
df = df.drop(loan_info_cols, axis=1)
这是我们迄今为止所拥有的:
print(df)
debt_type loan_info
0 credit_card {u'total_monthly_payment': 189.0, u'interest_p...
1 debit_card {u'total_monthly_payment': 165.0, u'interest_p...
现在您可以将整个数据帧转换为 JSON :
df_json = df.to_json(orient='records', lines=True)
print(df_json)
{"debt_type":"credit_card","loan_info":{"total_monthly_payment":189.0,"interest_payable":15356.0,"interest_rate":23.0,"debt_amount":9000.0,"remaining_term":129.0}}
{"debt_type":"debit_card","loan_info":{"total_monthly_payment":165.0,"interest_payable":21354.0,"interest_rate":24.0,"debt_amount":8000.0,"remaining_term":167.0}}
推荐阅读
- docker - GitHub 操作使用 CloudFlare 和 Traefik 构建 Docker 映像并将其推送到私有注册表,导致 413 实体太大
- vb.net - 如何确定 ME 的参考类型?
- forms - 将表单的 foreach 循环传递给 Twig
- excel - 将每个单元格具有多个值的集合从 Excel 导出到 CPLEX
- visual-studio - Visual Studio 命名空间类识别错误
- javascript - MatAutoComplete - 更改语言时更新显示在 displayWith 中的属性
- django - DRF测试多张图片上传
- python - 如何根据数据框中的另一列获取直方图 bin 中的哪些数据点?
- ruby-on-rails - 如何将参数保存到 form_with 方法发送的表中
- outlook - 在 wso2 ei 6.5.0 中从 MS Outlook 连接器获取未读电子邮件