Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace multiple pandas columns with constants from dictionary

I have a pandas dataframe like so:

import pandas as pd
df = pd.DataFrame({
    'id':[1,2,3,4,5,6],
    'a':[1,2,3,4,5,6],
    'b':['a', 'b', 'c', 'd', 'e', 'f']
})

And I would like to replace values in columns a and b with constants given by a dictionary like so:

fills = dict(
    a = 1,
    b = 'a'
)

to obtain a result like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   id   a   b
0   1   1   a
1   2   1   a
2   3   1   a
3   4   1   a
4   5   1   a
5   6   1   a

Obviously, I can do:

for column in fills:
   df.loc[:, column] = fills[column]

To get the desired results of:

    id  a   b
0   1   1   a
1   2   1   a
2   3   1   a
3   4   1   a
4   5   1   a
5   6   1   a

But is there perhaps some pandas function, that would let me pass the dictionary as an argument and to this replacement without writing a python loop?

>Solution :

You are right if columns names are not numbers – then is possible use DataFrame.assign:

df = df.assign(**fills)
print (df)
   id  a  b
0   1  1  a
1   2  1  a
2   3  1  a
3   4  1  a
4   5  1  a
5   6  1  a

Generally solution:

fills = {'a':4, 5:3}

for k, v in fills.items():
    df[k] = v
print (df)
   id  a  b  5
0   1  4  a  3
1   2  4  b  3
2   3  4  c  3
3   4  4  d  3
4   5  4  e  3
5   6  4  f  3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading