+3 votes
in Programming Languages by (15.7k points)

In a dataframe, I want to change some of the values in a column if a given value is present in another column. 

E.g., I want to change 28 to 128 in column 'C' if the column 'A' for the corresponding row has 10. How can I change it?

   A   B   C

0  10  14  28

1  20  15  29

2  30  16  30

3  40  17  31

4  50  18  32

1 Answer

+1 vote
by (27.2k points)

For such a change, you can provide the index of the pandas element you want to update in the attribute loc of the dataframe.

Here is an example.

The values of column A are keys and the new values of column C are values in the dictionary 't'.

import pandas as pd

df1 = pd.DataFrame({'A': [10, 20, 30, 40, 50], 'B': [14, 15, 16, 17, 18], 'C': [28, 29, 30, 31, 32]})

t = {10: 128, 30: 139, 40: 145}

print("original dataframe")

print(df1)

for k, v in t.items():

    df1.loc[df1['A'] == k, 'C'] = v

print("updated dataframe")

print(df1)

The above code will print the following outputs:

original dataframe

    A   B   C

0  10  14  28

1  20  15  29

2  30  16  30

3  40  17  31

4  50  18  32

updated dataframe

    A   B    C

0  10  14  128

1  20  15   29

2  30  16  139

3  40  17  145

4  50  18   32


...