Home > other >  How to change all values in a column (pandas), based on values in same row of different column
How to change all values in a column (pandas), based on values in same row of different column

Time:11-19

I have a csv as a data frame in python and as an example row of ages and year built:

AGE BUILT
82 2016

How can I change all the values in the age column of the df to equal the current year - the year the house was built (from built column)?

import pandas as pd

print('\n***Data Analysis for Housing CSV***')

housing_df = pd.read_csv('Housing.csv', header=0)

current_year = 2021

housing_df = housing_df.loc[housing_df['AGE'] != current_year - 
housing_df['BUILT'], 'AGE'] = current_year - housing_df[
'BUILT'] 

CodePudding user response:

housing_df["AGE"] = current_year - housing_df["BUILT"]

Edit: Pandas will understand you when you perform these arithmetic operations that look illogical between a column and an integer or a column and another column, example:

df["rectArea"] = df["height"] * df['width']
  • Related