Issue
Suppose I have this dataframe
data = {'Name': ["Bob", "Mike"],
'Age': ['32', '31'],
'Value': ['123.123', '124.56']}
df_test = pd.DataFrame(data=data)
df_test.head()
I want to create dictionary like this for each row
{'Age': '32',
'Value': '123.123'}
Such that I would get this
data = {'Name': ["Bob", "Mike"],
'Age': ['32', '31'],
'Value': ['123.123', '124.56'],
'parameters': [{'Age': '32', 'Value': '123,123'}, {'Age': 31, 'Value': '124.56'}]}
df_test = pd.DataFrame(data=data)
df_test.head()
How would I do this? I thought of creating a function and then just using .apply() but I am not exactly sure how to do it. Any help is appreciated.
Solution
Use DataFrame.to_dict
with parameter orient='records'
:
df_test['parameters'] = df_test[['Age','Value']].to_dict(orient='records')
print (df_test)
Name Age Value parameters
0 Bob 32 123.123 {'Age': '32', 'Value': '123.123'}
1 Mike 31 124.56 {'Age': '31', 'Value': '124.56'}
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.