python - 使用 Pandas 将 CSV 转换为嵌套的 JSON 复杂结构
问题描述
使用 Pandas 转换为嵌套的 JSON 文件
这是一行的示例 csv
name type aitm alitm aaitm adsc1
specs glass 70072187 ESA65Z45 ESA 65Z45 CUT TIP FG 1808-40
我正在尝试为每一行实现嵌套 JSON 的以下结构
解决方案
import pandas as pd
import json
df = pd.DataFrame([['specs','glass','70072187','ESA65Z45','ESA 65Z45','CUT TIP FG 1808-40'],
['specs','glass','666','ESA6665','ESB 666','CUT TIP FG 66-40']],
columns = ['name', 'type','aitm','alitm','aaitm','adsc1' ])
data = {'entities':[]}
for key,grp in df.groupby('name'):
for idx, row in grp.iterrows():
temp_dict_alpha = {'name':key, 'type':row['type'], 'data':{'attributes':{}}}
attr_row = row[~row.index.isin(['name','type'])]
for idx2, row2 in attr_row.iteritems():
dict_temp = {}
dict_temp[idx2] = {'values':[]}
dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_US'})
temp_dict_alpha['data']['attributes'].update(dict_temp)
data['entities'].append(temp_dict_alpha)
print(json.dumps(data, indent= 4))
输出:
print(json.dumps(data, indent= 4))
{
"entities": [
{
"name": "specs",
"type": "glass",
"data": {
"attributes": {
"aitm": {
"values": [
{
"value": "70072187",
"source": "internal",
"locale": "en_US"
}
]
},
"alitm": {
"values": [
{
"value": "ESA65Z45",
"source": "internal",
"locale": "en_US"
}
]
},
"aaitm": {
"values": [
{
"value": "ESA 65Z45",
"source": "internal",
"locale": "en_US"
}
]
},
"adsc1": {
"values": [
{
"value": "CUT TIP FG 1808-40",
"source": "internal",
"locale": "en_US"
}
]
}
}
}
},
{
"name": "specs",
"type": "glass",
"data": {
"attributes": {
"aitm": {
"values": [
{
"value": "666",
"source": "internal",
"locale": "en_US"
}
]
},
"alitm": {
"values": [
{
"value": "ESA6665",
"source": "internal",
"locale": "en_US"
}
]
},
"aaitm": {
"values": [
{
"value": "ESB 666",
"source": "internal",
"locale": "en_US"
}
]
},
"adsc1": {
"values": [
{
"value": "CUT TIP FG 66-40",
"source": "internal",
"locale": "en_US"
}
]
}
}
}
}
]
}
推荐阅读
- java - Spring Kafka - 代理重新连接事件
- swift - 为什么快速字符串中的“\ n”在略有不同的情况下表现不同?
- android - 如何将内容从文本文件复制到android中的数据库
- java - android条件语句检查char是否为单引号
- excel - 在一行中特定数量的单元格有内容后,如何取消编辑权限?
- sql - 在某些日期字符串上迭代 SQL 查询
- javascript - 提交 package-lock.json 值得麻烦吗?
- sql-server - 将参数从一个存储过程传递到另一个存储过程
- ionic-framework - 当应用程序在 Ionic 3 的抽屉中时如何更改应用程序导航栏颜色
- python - 是否可以为预训练的 Inception 模型(tensorflow 2.0/Keras)提供 2D 灰度图像?