I am trying to divide the entire dataframe by a fix number but I want to keep the 'Year' column as is. I tried dividing the entire df with 100 and then multiplying the 'Year' column by 100 and then converting it to integer but it rounds up some years which is really not ideal.
Is there any other way to use the loc as shown below but while excluding the 'Year' column from the calculations, keep it in the df.
Original input:
Code Used:
df1 = df1.drop(['HALF1', 'HALF2'], axis = 1)
df1 = df1.loc[:, df1.columns]/100
df1['Year'] = df1['Year']*100
df1['Year'] = df1['Year'].astype(int)
If I use the code below it removes the 'Year' from the df entirely.
#df1 = df1.loc[:, df1.columns != 'Year']/100
CodePudding user response:
Set "Year" as index, do the division, then reset_index
:
df = df.set_index("Year").div(100).reset_index()
Alternatively, divide all columns except "Year":
subset = df.columns.difference(["Year"])
df[subset] = df[subset].div(100)