excel_file name = exl.xlsx
Excel数据:
name surname email
a sname abc.com
b sname2 efg.com
json文件名= input.json
json数据
{
"a":
{
"friend1":4444444444,
"friend2":5555555555,
"friend3":1111111111
},
"b":
{
"friend3":6565656565,
"friend2":9999999999,
"friend5":9999988888
}
}
import json
import panda as pd
json_data = json.load(open(input.json))
data = pd.read_json(json_data)
excel_file = pd.read_excel(exl.xlsx, na_filter=False, header=0)
我想更新excel文件,使您将名称从json匹配到excel,并在excel中添加名为“listOfFriends”的新列,并为该匹配名称更新列
name surname email listOfFriends
a sname abc.com friend1, friend2, friend3
b sname2 efg.com friend3, friend2, friend5
答案 0 :(得分:1)
假设您从
开始j = """
{
"a":
{
"friend1":4444444444,
"friend2":5555555555,
"friend3":1111111111
},
"b":
{
"friend3":6565656565,
"friend2":9999999999,
"friend5":9999988888
}
}
"""
然后
pd.Series({k: list(v) for k, v in json.loads(j).items()}).to_frame().rename(columns={0: 'listOfFriends'})
给出
listOfFriends
a [friend1, friend2, friend3]
b [friend3, friend2, friend5]
如果您将此内容分配给friends
,则只需
pd.merge(excel_file, friends, left_on='name', right_index=True)
并将结果写回Excel文件。