excel_file name = exl.xlsx
Excel data:
name surname email
a sname abc.com
b sname2 efg.com
json file name = input.json
json data
{
"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)
I want to update excel file in such a way that you match the name from json to excel and add a new column in excel with name "listOfFriends" and for that matched name you update the column
name surname email listOfFriends
a sname abc.com friend1, friend2, friend3
b sname2 efg.com friend3, friend2, friend5
Say you start with
j = """
{
"a":
{
"friend1":4444444444,
"friend2":5555555555,
"friend3":1111111111
},
"b":
{
"friend3":6565656565,
"friend2":9999999999,
"friend5":9999988888
}
}
"""
Then
pd.Series({k: list(v) for k, v in json.loads(j).items()}).to_frame().rename(columns={0: 'listOfFriends'})
gives
listOfFriends
a [friend1, friend2, friend3]
b [friend3, friend2, friend5]
If you assign this to friends
, you just need to
pd.merge(excel_file, friends, left_on='name', right_index=True)
and write the results back to the Excel file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.