Python 3.x 从Dataframe创建嵌套JSON
我有一个数据帧,必须将其转换为嵌套的JSONPython 3.x 从Dataframe创建嵌套JSON,python-3.x,pandas,Python 3.x,Pandas,我有一个数据帧,必须将其转换为嵌套的JSON countryname name text score UK ABC Hello 5 现在,我有一些生成JSON的代码,将countryname和name分组。 但是,我想先按countryname分组,然后按name分组。以下是代码和输出: cols = test.columns.difference(['countryname','name']) j = (test.groupby(['countryname'
countryname name text score
UK ABC Hello 5
现在,我有一些生成JSON的代码,将countryname
和name
分组。
但是,我想先按countryname
分组,然后按name
分组。以下是代码和输出:
cols = test.columns.difference(['countryname','name'])
j = (test.groupby(['countryname','name'])[cols]
.apply(lambda x: x.to_dict('r'))
.reset_index(name='results')
.to_json(orient='records'))
test_json = json.dumps(json.loads(j), indent=4)
Output:
[
{
"countryname":"UK"
"name":"ABC"
"results":[
{
"text":"Hello"
"score":"5"
}
]
}
]
但是,我希望得到如下输出:
[
{
"countryname":"UK"
{
"name":"ABC"
"results":[
{
"text":"Hello"
"score":"5"
}
]
}
}
]
有人能帮忙解决这个问题吗?这将是有效的JSON。请注意,逗号
,
用法是必需的,您可以检查
您尝试实现的其他输出也不符合标准:
[{
"countryname": "UK",
"you need a name in here": {
"name": "ABC",
"results": [{
"text": "Hello",
"score": "5"
}]
}
}]
我改进了它,这样你就可以知道该用什么名字了。
对于自定义JSON输出,首先需要使用自定义函数重新格式化对象
l=df.to_dict('records')[0] #to get the list
print(l, type(l)) #{'countryname': 'UK', 'name': 'ABC', 'text': 'Hello', 'score': 5} <class 'dict'>
e = l['countryname']
print(e) # UK
o=[{
"countryname": l['countryname'],
"you need a name in here": {
"name": l['name'],
"results": [{
"text": l['text'],
"score": l['score']
}]
}
}]
print(o) #[{'countryname': 'UK', 'you need a name in here': {'name': 'ABC', 'results': [{'text': 'Hello', 'score': 5}]}}]
l=df.to_dict('records')[0]#获取列表
打印(l,键入(l)){'countryname':'UK','name':'ABC','text':'Hello','score':5}
e=l['countryname']
印刷品(e)#英国
o=[{
“countryname”:l['countryname'],
“这里需要一个名字”:{
“名称”:l[“名称”],
“结果”:[{
“文本”:l[“文本”],
“分数”:l[“分数”]
}]
}
}]
打印(o)#[{'countryname':'UK','这里需要一个名字':{'name':'ABC','results':[{'text':'Hello','score':5}]}]
我想先按countryname分组,然后按名称分组,其中包含值
l=df.to_dict('records')[0] #to get the list
print(l, type(l)) #{'countryname': 'UK', 'name': 'ABC', 'text': 'Hello', 'score': 5} <class 'dict'>
e = l['countryname']
print(e) # UK
o=[{
"countryname": l['countryname'],
"you need a name in here": {
"name": l['name'],
"results": [{
"text": l['text'],
"score": l['score']
}]
}
}]
print(o) #[{'countryname': 'UK', 'you need a name in here': {'name': 'ABC', 'results': [{'text': 'Hello', 'score': 5}]}}]