如何在Python中连接2个JSON对象

2024-10-08 19:31:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想基于某个列连接json对象,并创建一个包含两个json对象的列的输出。你知道吗

下面是输入和输出的示例

Json 1: 
Key    Value    identifier 
1111    Y          1
2222    N          1
3333    Y          2
4444    N          1


JSON2:
ID        name     address      zip      mobile
1111      SRI      Guntur       522438   999999
2222      Ravi     Medikonduru  522238   888888
5555      kavitha  Goa          789889   777777
4444      power    SAP          827736   666666



Result:
ID        name     address      zip      mobile  Value
1111      SRI      Guntur       522438   999999   Y
2222      Ravi     Medikonduru  522238   888888   N
4444      power    SAP          827736   666666   N      


Tags: 对象nameidjson示例valueaddresszip
2条回答

您可以使用下面的代码来查找结果

import pandas as pd

json_1 = pd.DataFrame({"key":["1111","2222","3333","4444","5555"],
                       "value":["Y","N","Y","N","Y"],
                       "identifier":[1,2,1,2,1]
                    })

json_2 = pd.DataFrame({"id" : ["1111","2222","3333","4444","5555"], 
                     "Name" : ["Sri","Ravi","Kavitha","Ramesh","Power"],
                     "Address":["Guntur","SAP","Vizag","Goa","Delhi"],
                     "Zip":[1,2,3,4,5],
                     "Mobile":[11,22,33,44,55]
                     })


json_2.join(json_1.set_index('key'), on='id')  

非熊猫解决方案:

import pandas as pd

json1 = {"key":["1111","2222","3333","4444"],
                       "Value":["Y","N","Y","N"],
                       "identifier":[1,1,2,1]
                    }

json2 = {"ID" : ["1111","2222","5555","4444"], 
                     "name" : ["SRI","Ravi","kavitha","power"],
                     "address":["Guntur","Medikonduru","Goa","SAP"],
                     "zip":[522438,522238,789889,827736],
                     "mobile":[999999,888888,777777,666666]
                     }
result = {}
include = []

for key_index in range(0,len(json1["key"])):
    if json1["key"][key_index] in json2["ID"]:
        include.append(key_index)

for key in json1.keys():
    result[key] = [json1[key][i] for i in include]        
for key in json2.keys():
    result[key] = [json2[key][i] for i in include]    

print(pd.DataFrame(result))

相关问题 更多 >

    热门问题