# [Python] how to update one column of a dataframe based on the value on another column

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 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
{"ft_lang_label":"__label__en","ft_lang_prob":0.5191005,"math_prob":0.9677847,"size":738,"snap":"2022-05-2022-21","text_gpt3_token_len":282,"char_repetition_ratio":0.115803815,"word_repetition_ratio":0.0794702,"special_character_ratio":0.48373982,"punctuation_ratio":0.17010309,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9711869,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-20T04:49:48Z\",\"WARC-Record-ID\":\"<urn:uuid:f16c0e5c-7db3-41db-841d-7ce324aae56e>\",\"Content-Length\":\"39226\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:5a01b7cf-95e7-41df-9e9a-25b956ff2a52>\",\"WARC-Concurrent-To\":\"<urn:uuid:ab1a21d6-45a2-433e-900d-905ac7460485>\",\"WARC-IP-Address\":\"139.64.237.67\",\"WARC-Target-URI\":\"https://www.discoverbits.in/2860/python-update-column-dataframe-based-value-another-column\",\"WARC-Payload-Digest\":\"sha1:2PBDSCU6LQHCDVPGR6ZN6WRTOTXX3FHP\",\"WARC-Block-Digest\":\"sha1:TI63OUM53SS7KZJCQKYRI6DKLE76E66J\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652662531352.50_warc_CC-MAIN-20220520030533-20220520060533-00423.warc.gz\"}"}