python - 如何使用python将两个excel列转换为json?
问题描述
我有一个类似这样的excel文件:
name gender fac1(radio) fac2(tv) fac3(cycle) fac4(bike) hasCard cardNo
a1 f y y n y n
a2 m n n y n y AHJS5684
如何从上面的 xls 文件中获得如下结构
"name": "a1",
"gender": "f",
"facilities": ["radio", "tv", "bike"],
"card": {
"exists": "n"
"cardNo": ""
}
到目前为止,我刚刚在我的代码中阅读了 excel 文件:
import pandas as pd
#reading excel
df = pd.read_excel("C:\\Users\\Desktop\\Culture\\Artist_Data\\EZCC\\Madur.xlsx")
new_df = df.assign(facilities = df.filter(like = 'fac').apply(lambda x: x.str.lower().dropna().tolist(), axis=1))
d = df.to_dict('records')
上面的代码根本没有给出想要的结果。
解决方案
Pandas 非常适合作为数据帧处理,而不是 json 格式。但是apply
可以将数据帧的行(或列)转换为包括字典在内的任何内容,list
并将熊猫系列简单地转换为列表。
这意味着所需的转换可以是:
labels = {'fac1(radio)': 'radio', 'fac2(tv)': 'tv', 'fac3(cycle)': 'cycle',
'fac4(bike)': 'bike' }
d = list(df.fillna('').apply(lambda x: {
"name": x['name'],
"gender": x['gender'],
"facilities": [labels[i] for i in labels.keys() if x[i] == 'y'],
"card": {
"exists": x['hasCard'],
"cardNo": x['cardNo']
}}, axis=1))
你可以控制它
print(json.dumps(d, indent=2))
按预期给出:
[
{
"name": "a1",
"gender": "f",
"facilities": [
"radio",
"tv",
"bike"
],
"card": {
"exists": "n",
"cardNo": ""
}
},
{
"name": "a2",
"gender": "m",
"facilities": [
"cycle"
],
"card": {
"exists": "y",
"cardNo": "AHJS5684"
}
}
]
推荐阅读
- google-analytics - 使用 Measurement Protocol (GA4) 设置 debug_mode
- html - 单个网页上的 14 个 Bootstrap 4.5 轮播
- c# - 如何检查是否使用 MailKit 发送了电子邮件
- user-interface - 如何仅使用键盘在 Colab 中显示/隐藏自动完成弹出窗口?
- java - 如何将跟踪级别和一个具有调试级别的包写入单个文件
- scala - 如何在scala中将csv文件读入地图
- python - 从 python 创建 Excel 宏
- python-3.x - 具有 Postgres 模式和 SQLAlchemy ORM 的多租户 - 连接、会话和选项健全
- python - Python IndexError 在使用带有 range() 和 len() 的 for 循环
- vivado - $display 在测试台中无法正常工作