Home > database >  How to add a column to a dataframe pandas so its value is dict?
How to add a column to a dataframe pandas so its value is dict?

Time:10-29

I have a directory with the following structure:

value_students_shop = {'hypermarket': 0.143,
                       'supermarket': 0.125, 
                       'small_shop': 0.15}

And, for example, the following data set:

df
col1   col2
1      1
2      2
3      3
4      4

I need to create a new column in the dataframe so that its values ​​are a dict, that is, I need the following result:

df
col1   col2   col3
1      1      {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15}
2      2      {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15}
3      3      {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15}
4      4      {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15}

How can I do that?

CodePudding user response:

here is one way about it

df['col3'] = str(value_students_shop)
df
    col1    col2    col3
0   1   1   {'hypermarket': 0.143, 'supermarket': 0.125, '...
1   2   2   {'hypermarket': 0.143, 'supermarket': 0.125, '...
2   3   3   {'hypermarket': 0.143, 'supermarket': 0.125, '...
3   4   4   {'hypermarket': 0.143, 'supermarket': 0.125, '...
you can access values in dictionary as follows, using literal_eval
df['col3'].apply(literal_eval)[0]['hypermarket']
>>> 0.143

alternate solution

# wrap the dictionary in a list, it get stores as a dictionary
df['col3']=[value_students_shop]*len(df)
df
    col1    col2    col3
0   1   1   {'hypermarket': 0.143, 'supermarket': 0.125, '...
1   2   2   {'hypermarket': 0.143, 'supermarket': 0.125, '...
2   3   3   {'hypermarket': 0.143, 'supermarket': 0.125, '...
3   4   4   {'hypermarket': 0.143, 'supermarket': 0.125, '...
when wrapping in a list, you can access dictionary values as follows

df['col3'][0]['hypermarket']
>>> 0.143

CodePudding user response:

please try this you can use str() instead of json.dumps. but when you revert it to dictionary using json.loads(), it is better to use json.dumps


import json
df['col3'] = json.dumps(value_students_shop)

  • Related