On a single dataframe, I can drop columns using the conventional df = df.drop('column name'). But when I try to loop over multiple dataframes and apply drop() to each one, the changes are not persistent. I know there is an inplace='True' argument that I can use but I am confused by what is fundamentally going on inside the for loop.
Example:
df_1 = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
df_1
A B
0 1 4
1 2 5
2 3 6
df_2 = pd.DataFrame({'A':[10,20,30], 'C':[40,50,60]})
df_2
A C
0 10 40
1 20 50
2 30 60
# this is the behavior I am looking for.
df_1 = df_1.drop('A', axis=1)
df_1
B
0 4
1 5
2 6
# when I put 2 dataframes in a for loop, I do not get the same output.
df_1 = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
df_2 = pd.DataFrame({'A':[10,20,30], 'C':[40,50,60]})
full_data = [df_1, df_2]
# I expect this code to apply the "drop" for each of these dataframes in the same way
# as above without the need for the "inplace" argument.
for dataset in full_data:
dataset = dataset.drop('A', axis=1)
# the column 'A' should have been dropped for each dataframe while inside the loop
# but it wasnt. why?
df_1
A B
0 1 4
1 2 5
2 3 6