-1

I would like to loop over two dataframes df1 and df2. These frames have the same columns and I would like to remove rows containing 12 as a value in col2.

The code that works for a single datafareme is the below:

df1 = df1[df1['col2'] != 12]

I have tried to create a list and loop over this list but is seem incorrect:

y = [df1, df2]

for x in y:
    x = x[x['col2'] != 12]
Caiotru
  • 335
  • 1
  • 10
  • 3
    You are reassigning `x` inside the loop. Your loop doesn't modify the original dfs in place, but rather, creates a filtered copy of each (that you immediately discard). – 0x5453 Sep 29 '20 at 13:50
  • It may be easier to just [`pd.concat`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html) the two dataframes into one. – 0x5453 Sep 29 '20 at 13:50
  • 1
    Does this answer your question? [How to modify list entries during for loop?](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) – 0x5453 Sep 29 '20 at 13:53
  • Thank you@0x5453, are you able to provide the correct code as an example? – Caiotru Sep 29 '20 at 14:03

1 Answers1

0

As 0x5453 noticed, you need to change the dataframes in place, like this for example :

y = [df1, df2]
for i, x in enumerate(y):
    y[i] = x[x['col2'] != 12]
Phoenixo
  • 2,071
  • 1
  • 6
  • 13
  • Thank you @phoenixo, can I modify each single df with the loop? so if I print df1 or df2 I will get the output without 12 as a value.. – Caiotru Sep 29 '20 at 15:04
  • Yes the for loop is modifying all df, so if you print them at the end you will get the expected result without value 12 – Phoenixo Sep 29 '20 at 15:38