[英]Construct JSON from pandas data frame
I have this panda data frame containg info about id, description, field name, field value and email我有这个熊猫数据框包含有关 id、描述、字段名称、字段值和 email 的信息
id desc field_name val eml
0 1 desc in id 1 field_1 300 test@gmail.com
1 1 desc in id 1 field_2 305 test@gmail.com
2 2 desc in id 2 field_3 530 test2@gmail.com
3 2 desc in id 2 field_4 745 test2@gmail.com
3 2 desc in id 2 field_1 845 test2@gmail.com
Here desc and email will be same for a particular id So I want to construct an array of JSON by clubbing the id, desc and email这里 desc 和 email 对于特定的 id 将是相同的所以我想通过合并 id、desc 和 email 来构造一个 JSON 数组
And all the changes on field name and val will be send by list of list format并且字段名称和值的所有更改都将通过列表格式列表发送
[
{
id: 1,
desc: "desc in id 1",
eml: "test@gmail.com"
values: [ [field_1, 300], [field_2, 305] ]
},
{
id: 2,
desc: "desc in id 2",
eml: "test2@gmail.com"
values: [ [field_3, 530], [field_4, 745], [field_1, 845] ]
},
]
(If you google "pandas to json" the first hit is the link below...) (如果你用谷歌搜索“pandas to json”,第一个点击是下面的链接......)
You can use the pd.to_json
ie您可以使用pd.to_json
即
df_json = df.to_json()
where the argument orient
defines different outputs.其中参数orient
定义不同的输出。 You'll most likely use orient="records"
to get it as a json-array eg您很可能会使用orient="records"
将其作为 json-array 获取,例如
import pandas as pd
df_so = pd.DataFrame({"id":[1,2,3],"email":["foo@example.com","bar@example.com","baz@example.com"]})
print(df_so)
# id email
# 0 1 foo@example.com
# 1 2 bar@example.com
# 2 3 baz@example.com
df_so.to_json(orient="records")
#
#[{"id":1,"email":"foo@example.com"},
#{"id":2,"email":"bar@example.com"},
#{"id":3,"email":"baz@example.com"}]'
regarding your values
you'll need to create that column first.关于您的values
,您需要先创建该列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.