从每一行创建字典的字典,并将每一行导出为 json 文件 python
Create dictionary of dictionary from each row and export each row as a json file in python
我有一个 pandas 数据框,如下所示
我想为每一行创建一个字典,如下所示。字典列表中的特征。
#row1 示例输出。它应该跳过 null 属性 face 和 hat。
{
"name": "rv",
"image": "https://img0.png",
"attributes": [
{ "trait_type": "background", "value":"grey" },
{ "trait_type": "tshirt", "value":"yellow" },
{ "trait_type": "eagle", "value":"male" },
{ "trait_type": "hair", "value":"darktwists" }
]
}
#row3 示例输出。它应该跳过 null 属性 face 和 hair。
{
"name": "nv",
"image": "https://img2.png",
"attributes": [
{ "trait_type": "background", "value":"brown" },
{ "trait_type": "tshirt", "value":"americanflag" },
{ "trait_type": "eagle", "value":"male" },
{ "trait_type": "hat", "value":"policehat" }
]
}
像这样,每一行输出都应该存储在一个单独的JSON文件中。
我尝试使用 lambda apply 和 _to_json 进行此操作,但遇到了两个问题:
1) 无法以所需格式将属性打包为字典中的单独字典。
2)JSON 将 HTTPS 图像 link 中的正斜杠“//”存储为“/”
非常感谢任何帮助。谢谢。
首先,您需要融化 df 以针对字典中的 "attribute"
键构建它,并相应地重命名列:
df = df.melt(id_vars=['name','image'])
df = df.rename(columns={'variable':"trait_type"})
然后我们需要根据名称和图像(以及您要包含在 json 结构中的其他唯一值)对它们进行分组。然后遍历组并构建字典结构:
results = []
for index, group in df.groupby(['name','image']):
temp_dict = {}
temp_dict["name"] = index[0]
temp_dict["image"] = index[1]
temp_dict["attributes"] = group[["trait_type","value"]].to_dict("records")
results.append(temp_dict)
这应该会给出您喜欢的结果。
紧凑型答案(Timus 建议):
您可以在一行中完成整个操作:
dicts = (df.melt(id_vars=['name', 'image'], var_name='trait_type')
.dropna()
.groupby(['name', 'image'])[['trait_type', 'value']]
.apply(pd.DataFrame.to_dict, orient='records')
.reset_index(drop=False)
.rename(columns={0: 'attributes'})
.to_dict(orient='records'))
首先:你的JSON格式不是泛型格式,所以不能直接用pandasto_json()
and/or[=14创建=] 数据帧的方法,所以你需要手动处理它
第二件事:pandas 默认添加转义字符,这就是 'https://img0.png'
被 https:\/\/img0.png
替换的原因
out=(df.assign(attributes=df[['background', 'tshirt', 'eagle', 'face', 'hat']]
.apply(lambda x:[{'trait_type':index, 'value':value}
for index, value in x[x.notna()].iteritems()],
axis=1))
[['name', 'image', 'attributes']]
.apply(dict, axis=1)
.tolist()
)
输出:
[
{
'name': 'rv',
'image': 'https://img0.png',
'attributes': [
{'trait_type': 'background', 'value': 'gray'},
{'trait_type': 'tshirt', 'value': 'yellow'},
{'trait_type': 'eagle', 'value': 'male'}
]
},
{
'name': 'cv',
'image': 'https://img1.png',
'attributes': [
{'trait_type': 'background', 'value': 'yellow'},
{'trait_type': 'tshirt', 'value': 'green'},
{'trait_type': 'eagle', 'value': 'male'}
]
}
]
在此之后,您将在变量 out
中得到一个字典列表,您可以将其传递给 json.dumps
以从中创建 json,看起来像下面:
>>> import json
>>> print(json.dumps(out, indent=4)
[
{
"name": "rv",
"image": "https://img0.png",
"attributes": [
{
"trait_type": "background",
"value": "gray"
},
{
"trait_type": "tshirt",
"value": "yellow"
},
{
"trait_type": "eagle",
"value": "male"
}
]
},
{
"name": "cv",
"image": "https://img1.png",
"attributes": [
{
"trait_type": "background",
"value": "yellow"
},
{
"trait_type": "tshirt",
"value": "green"
},
{
"trait_type": "eagle",
"value": "male"
}
]
}
]
我有一个 pandas 数据框,如下所示
我想为每一行创建一个字典,如下所示。字典列表中的特征。
#row1 示例输出。它应该跳过 null 属性 face 和 hat。
{
"name": "rv",
"image": "https://img0.png",
"attributes": [
{ "trait_type": "background", "value":"grey" },
{ "trait_type": "tshirt", "value":"yellow" },
{ "trait_type": "eagle", "value":"male" },
{ "trait_type": "hair", "value":"darktwists" }
]
}
#row3 示例输出。它应该跳过 null 属性 face 和 hair。
{
"name": "nv",
"image": "https://img2.png",
"attributes": [
{ "trait_type": "background", "value":"brown" },
{ "trait_type": "tshirt", "value":"americanflag" },
{ "trait_type": "eagle", "value":"male" },
{ "trait_type": "hat", "value":"policehat" }
]
}
像这样,每一行输出都应该存储在一个单独的JSON文件中。
我尝试使用 lambda apply 和 _to_json 进行此操作,但遇到了两个问题: 1) 无法以所需格式将属性打包为字典中的单独字典。 2)JSON 将 HTTPS 图像 link 中的正斜杠“//”存储为“/”
非常感谢任何帮助。谢谢。
首先,您需要融化 df 以针对字典中的 "attribute"
键构建它,并相应地重命名列:
df = df.melt(id_vars=['name','image'])
df = df.rename(columns={'variable':"trait_type"})
然后我们需要根据名称和图像(以及您要包含在 json 结构中的其他唯一值)对它们进行分组。然后遍历组并构建字典结构:
results = []
for index, group in df.groupby(['name','image']):
temp_dict = {}
temp_dict["name"] = index[0]
temp_dict["image"] = index[1]
temp_dict["attributes"] = group[["trait_type","value"]].to_dict("records")
results.append(temp_dict)
这应该会给出您喜欢的结果。
紧凑型答案(Timus 建议):
您可以在一行中完成整个操作:
dicts = (df.melt(id_vars=['name', 'image'], var_name='trait_type')
.dropna()
.groupby(['name', 'image'])[['trait_type', 'value']]
.apply(pd.DataFrame.to_dict, orient='records')
.reset_index(drop=False)
.rename(columns={0: 'attributes'})
.to_dict(orient='records'))
首先:你的JSON格式不是泛型格式,所以不能直接用pandasto_json()
and/or[=14创建=] 数据帧的方法,所以你需要手动处理它
第二件事:pandas 默认添加转义字符,这就是 'https://img0.png'
被 https:\/\/img0.png
out=(df.assign(attributes=df[['background', 'tshirt', 'eagle', 'face', 'hat']]
.apply(lambda x:[{'trait_type':index, 'value':value}
for index, value in x[x.notna()].iteritems()],
axis=1))
[['name', 'image', 'attributes']]
.apply(dict, axis=1)
.tolist()
)
输出:
[
{
'name': 'rv',
'image': 'https://img0.png',
'attributes': [
{'trait_type': 'background', 'value': 'gray'},
{'trait_type': 'tshirt', 'value': 'yellow'},
{'trait_type': 'eagle', 'value': 'male'}
]
},
{
'name': 'cv',
'image': 'https://img1.png',
'attributes': [
{'trait_type': 'background', 'value': 'yellow'},
{'trait_type': 'tshirt', 'value': 'green'},
{'trait_type': 'eagle', 'value': 'male'}
]
}
]
在此之后,您将在变量 out
中得到一个字典列表,您可以将其传递给 json.dumps
以从中创建 json,看起来像下面:
>>> import json
>>> print(json.dumps(out, indent=4)
[
{
"name": "rv",
"image": "https://img0.png",
"attributes": [
{
"trait_type": "background",
"value": "gray"
},
{
"trait_type": "tshirt",
"value": "yellow"
},
{
"trait_type": "eagle",
"value": "male"
}
]
},
{
"name": "cv",
"image": "https://img1.png",
"attributes": [
{
"trait_type": "background",
"value": "yellow"
},
{
"trait_type": "tshirt",
"value": "green"
},
{
"trait_type": "eagle",
"value": "male"
}
]
}
]