Python-Pandas: how to avoid the keyerror while changing the df inplace

Viewed 65

Example

Creating test df

def f_test_df(n_rows, n_cols):
    df1 = pd.DataFrame(np.random.rand(n_rows, n_cols))
    df = df1.applymap(lambda x: round(x*10))
    return df 

np.random.seed(seed=1)
df1 = f_test_df(7, 7)

enter image description here

Now, carrying out an inplace operation that changes the original dataframe itself.

df1.drop(columns=[2, 3, 4, 5, 6],
         inplace=True)

enter image description here

If the above line is run again, it would lead to a key error, since the df has changed now. The same is true for all other operations that change the dataframe itself.

The solution is to use a try-except construct, as shown below:

try:
    df1.drop(columns=[2, 3, 4, 5, 6],
             inplace=True)
    pass
except:
    pass

Now, the earlier keyerror is avoided.

Question

However, this is not an elegant solution. Is there a more pythonic way to achieve the same? How to avoid the KeyError when changing the original df itself?

1 Answers

pd.DataFrame.drop() has the errors argument:

df1.drop(columns=[2,3,4,5,6], inplace=True, errors='ignore')

So just specify errors='ignore' and it won't throw an error. errors default value is raise, which would raise a KeyError if the columns aren't present.

Related