How do I change a cell's contents within an if statement?

Viewed 77

Here I'm trying make the cell for the days_employed column in the row that has 'retiree' in a different column into NaN. As it is, it makes the entire days_employed column into NaN, whereas I only want that specific cell in that row to be NaN

for row in df['income_type']: 
    if row == 'retiree':
        df['days_employed'] = float('Nan')

Is there something similar to row in df['days_employed'] = float('Nan')?

2 Answers

Since this seems like pandas to me, you can vectorize this by applying a condition on the entire column, then assigning those cells to NaN:

df.loc[df['income_type'].eq('retiree'), 'days_employed'] = np.nan

Or, reassign the column using np.wher:

df['days_employed'] = np.where(
    df['income_type'].eq('retiree'), np.nan, df['days_employed'])

When you do list[column] you are specifying the entire column, that is why the entire days_employed is being changed to NaN. Try this and let me know if it works:

for row in df['income_type']: 
    if row == 'retiree':
        df['days_employed'][x] = float('Nan')

Note: x is the specific value in ['days_employed'] that should be changed to float('Nan').

If you do not know the value of the cell you want to change, or if it changes often, then simply use a for loop to look for the index of the cell you want to change, and set x to that index.

Related