Reputation: 79
I need to create a pandas data frame from different dictionaries where keys must act as column names inside the data frame. If the data frame doesn't have the key listed as a column, then it has to create it dynamically and attached as a new column to the data frame.
I expect the input as,
1st dict-> {'mse': 0.04, 'accuracy': 0.91, 'mean':0.75}
2nd dict-> {'mse': 0.04, 'accuracy': 0.91}
3rd dict-> {'mse': 0.04, 'accuracy': 0.91, 'f1-score':0.95}
And the output should be,
1st iteration of a loop it takes keys as columns name for data frame and creates if no data frame present with values as 1st row.
2nd iteration checks if keys are present as columns in the data frame and insert if already present else create a column and insert values as 2nd row.
I exactly don't know how to run the loop dynamically in python. Can anyone please help me in resolving the issue? Thanks in advance!
Upvotes: 1
Views: 972
Reputation: 32011
here is the docs from_records
import pandas as pd
dict = {'mse': 0.04, 'accuracy': 0.91, 'mean':0.75}
dict2 = {'mse': 0.04, 'accuracy': 0.91}
dict3 = {'mse': 0.04, 'accuracy': 0.91, 'f1-score':0.95}
mydicts = [dict, dict2, dict3]
df = pd.DataFrame.from_records(mydicts).fillna(0)
print(df)
or simply that said in comments
pd.DataFrame(mydicts)
Upvotes: 3