How to loop through 2 columns in a dataframe and replace the value in another column with something else?

Question:

So I need to find replace the value for annual_data[‘countyfips’] from ‘NA’ to 5097 where annual_data [‘BUYER_STATE’] == ‘AR’ and annual_data[‘BUYER_COUNTY’] == ‘MONTGOMERY’.

Below is my code:

annual_data = annual_data[['BUYER_COUNTY', 'BUYER_STATE', 'year', 'DOSAGE_UNIT', 'countyfips']]
annual_data

for index, values in annual_data.iterrows():
    if (values['BUYER_STATE'] == 'AR') and (values['BUYER_COUNTY'] == 'MONTGOMERY'):
        annual_data.at[index, 'countyfips'] == 5097
print(annual_data)

However, annual_data[‘countyfips’] still equals ‘NA’.

Asked By: rerecodes

||

Answers:

Change the == to = here:

From

    annual_data.at[index, 'countyfips'] == 5097

to

    annual_data.at[index, 'countyfips'] = 5097
Answered By: Eureka
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.