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)
Now, carrying out an inplace operation that changes the original dataframe itself.
df1.drop(columns=[2, 3, 4, 5, 6],
inplace=True)
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?

