Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply loc to the entire dataframe but one column (keep the one column as it was and not remove it)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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)

Desired output:
enter image description here

If I use the code below it removes the ‘Year’ from the df entirely.

#df1 = df1.loc[:, df1.columns != 'Year']/100

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading