Reputation: 390
I have this json object name_lookup like below:
[
{
"ID": "70B52DA6-F099-4D01-BBD0-03EA97292C26",
"Name": "Join"
},
{
"ID": "442B1598-20CF-4425-8A28-0438FBF77C46",
"Name": "Bob"
}
]
My dataframe (df) have structure:
Id Name
Join
Bob
How can I loop through Json object above and compare name to fill in id in df?
I use this function to load json file:
def read_configs(file_name):
with open(file_name, "r", encoding='utf-8') as read_file:
lookup = json.load(read_file)
return lookup
Please help me. Many thanks to your help <3
Upvotes: 1
Views: 1257
Reputation: 23780
Assuming names are unique, it is possible to use map
function of Pandas:
import pandas as pd
lookup = [
{
"ID": "70B52DA6-F099-4D01-BBD0-03EA97292C26",
"Name": "Join"
},
{
"ID": "442B1598-20CF-4425-8A28-0438FBF77C46",
"Name": "Bob"
}
]
df = pd.DataFrame([[None, "Join"], [None, "Bob"]], columns=["ID", "Name"])
# Convert the list of entities to a dictionary and map names by it
df["ID"] = df["Name"].map({entity["Name"]: entity["ID"] for entity in lookup})
Upvotes: 2