Skip to content
Advertisement

How to replace multiple column values for specific row in python dataframe?

I have dataframe with thousand columns, I want to replace a few columns (which I stored in a dictionary) for a specific row, how can I do that?

    my_dict={'a':2,'b':1} #total feature is more than this.
    Df.loc[i]=my_dict #i is row index

If you have another method to do without considering the dictionary then please suggest me, I will twerk my code accordingly. I just want to complete this operation.

Advertisement

Answer

Say you have this input data:

df = pd.DataFrame({'a':[1,2],'b':[3,4], 'c':[5,6]})
d = {'a':2,'b':1}
i = 0

Then you can do:

df.loc[i,d.keys()] = d.values()

df output:

    a   b   c
0   2   1   5
1   2   4   6
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement