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

why this try except doesn't work when renaming pandas column?

I am trying to rename one of pandas columnns, and use try except for the cases with different column names.

Here is the data before using try and except.

df_data=pd.read_csv(file_GG,sep='\t')
print('data_early')
print(df_data)
df_data=df_data.rename(columns={'MD':'WellMD'})
df_data
data_early
          MD  Shallow_Res_ohmm
0     1031.7              8.14
1     1031.8             10.04
2     1031.9             10.11

    WellMD  Shallow_Res_ohmm
0   1031.7  8.14
1   1031.8  10.04
2   1031.9  10.11
3   1032.0  7.61
4   1032.1  5.12

Now I’d like to change the other column name which might have different names, so I use try and except

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

try:
    df_data=df_data.rename(columns={'Deep_Res_ohmm':'new_name'})
except:
    print('testing different column name')
    df_data=df_data.rename(columns={'Shallow_Res_ohmm':'new_name'})
    

print('df_after')
print(df_data)

df_after
      WellMD  Shallow_Res_ohmm
0     1031.7              8.14
1     1031.8             10.04
2     1031.9             10.11

so you can see the code never go to except section and column name remain the same.

>Solution :

Because the default behavior of the rename method is to "ignore" errors (for the current pandas version at least). So despite not finding that column in your try, no exception is raised. Try this instead.

df_data=df_data.rename(columns={'Deep_Res_ohmm':'new_name'}, errors='raise')

here is the documentation for the rename method. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rename.html

There is probably better ways of doing this, but I wanted to address your specific question of why the try wasn’t raising an exception.

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