Home > Net >  Creating a dictionary object column from two other columns in a pandas dataframe
Creating a dictionary object column from two other columns in a pandas dataframe

Time:09-13

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.

CodePudding user response:

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'}

CodePudding user response:

You can use to_dict with orient='index':

df_test['parameters'] = pd.Series(df_test.drop(columns='Name').to_dict('index'))

output:

   Name Age    Value                         parameters
0   Bob  32  123.123  {'Age': '32', 'Value': '123.123'}
1  Mike  31   124.56   {'Age': '31', 'Value': '124.56'}
  • Related