Delete column from pandas DataFrame

后端 未结 17 1388
一生所求
一生所求 2020-11-22 02:44

When deleting a column in a DataFrame I use:

del df[\'column_name\']

And this works great. Why can\'t I use the following?

         


        
17条回答
  •  心在旅途
    2020-11-22 03:32

    In pandas 0.16.1+ you can drop columns only if they exist per the solution posted by @eiTanLaVi. Prior to that version, you can achieve the same result via a conditional list comprehension:

    df.drop([col for col in ['col_name_1','col_name_2',...,'col_name_N'] if col in df], 
            axis=1, inplace=True)
    

提交回复
热议问题