Home > Net >  How to assign a python object (such as a dictionary) to pandas column?
How to assign a python object (such as a dictionary) to pandas column?

Time:04-27

I am trying to assign a dictionary object to all cells in a pandas data frame.

sample df:

     name    roll    
0    tom       2
1    jon      10
2    mark     125
.
.
.
.
.
150   kevin   1250   

Here i was able to assign a value directly - df['class']='Class A'

     name    roll     class
0    tom       2     Class A
1    jon      10     Class A
2    mark     125    Class A
.                       .
.                       .
.                       .
.                       .
.                       .
150   kevin   1250   Class A

How to do the same with python object:

Required output:

     name    roll     class
0    tom       2     {'class':'Class A'}
1    jon      10     {'class':'Class A'}
2    mark     125    {'class':'Class A'}
.                       .
.                       .
.                       .
.                       .
.                       .
150   kevin   1250   {'class':'Class A'}
   

CodePudding user response:

Try:

df["class"] = [{"class": "Class A"}]*len(df)

>>> df
    name  roll                 class
0    Tom     2  {'class': 'Class A'}
1    Jon    10  {'class': 'Class A'}
2   Mark   125  {'class': 'Class A'}
3  Kevin  1250  {'class': 'Class A'}
  • Related