I am dealing with pandas DataFrame (df) within a for loop that may have different columns. For example, for the first loop, df may have columns: "A", "B", "C", "D", and "E". For the second loop, df may have columns: "B", "C", "E", "F", "G", and "H". I want to drop certain columns e.g., "A" , "F", and "G" from df. If I use the line below within the for loop, It will result an error: "[‘F’ ‘G’] not found in axis."
df = df.drop(['A', 'F', 'G'], axis=1)
Similarly, for the second loop, It will result an error: "[‘A’] not found in axis." How to solve this problem?
>Solution :
Try with pass errors = 'ignore'
out = df.drop(["A","F","G"], errors = 'ignore', axis = 1)