0

I have a column in my df with year values as INT but some values are 0. I'm trying to run a for loop to keep the 0 values but replace the year values with a calc (i.e 2020 - value in column). So far I have:

for (i, item) in enumerate(housing['YrRenovated']):
     if item > 0:
      housing['YrRenovated'][i] = 2020 - item,
     else: 
      housing['YrRenovated'] = 0,
    
    

It runs but the max value in the column is 0 when it should be like 45

Josh Ortega
  • 179
  • 8
  • Would you kindly provide a sample input and output? Check this: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – O. Mohsen Aug 11 '20 at 04:40
  • ``np.where(df['YrRenovated'] > 0, 2020 - df['YrRenovated'], 0)`` – sushanth Aug 11 '20 at 04:44

2 Answers2

0

try using apply and lambda functions.

housing['YrRenovated'] = housing['YrRenovated'].apply(lambda item: 2020-item if item > 0 else 0)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Faizan Naseer
  • 589
  • 3
  • 12
0

Try using the following loop:

for index, row in housing.iterrows():
    if row['YrRenovated'] != 0:
        newValue = 2020 - row['YrRenovated']
        housing.at[index, 'YrRenovated'] = newValue
O. Mohsen
  • 179
  • 1
  • 6