Home > Blockchain >  Replace multiple pandas columns with constants from dictionary
Replace multiple pandas columns with constants from dictionary

Time:02-16

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:

   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?

CodePudding user response:

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
  • Related