0

Hello Pythoners and Pythonistas,

I am trying to filter multiple dataframes based on a list of names. I wrote this code, but I am not sure why is not working.

df1= {"Name" :["Name1", "Name2", "Name3", "Name4"],
      "X":[30,40,50,60],
      "Y":[20,30,10,40],
      "Z":[10,20,20,10]}

dfs = [df1, df2, df3, df4]
name_lists = ['name1','name2','name3','name5'] 
for dataframe in dfs:
      dataframe = dataframe[dataframe["ColumnName"].isin(name_lists)]

Any suggestion is more than welcomed. Thank you, Qtry

Qthry
  • 45
  • 6
  • 2
    You're creating a new variable `dataframe` in each iteration of the loop, not modifying the existing values in the list dfs. Accessing by index would work `dfs[0] = ...` for example. – Henry Ecker Oct 08 '21 at 15:51
  • What would be the output? – Dani Mesejo Oct 08 '21 at 15:53
  • thanks both. @HenryEcker so the code will look something like: `dfs[0]= dataframe[dataframe["ColumnName"].isin(name_lists)]` – Qthry Oct 08 '21 at 15:58
  • @DaniMesejo my output will be a new dataframe containing only the values in the list – Qthry Oct 08 '21 at 16:00
  • Take a look at [this answer](https://stackoverflow.com/a/19290848/15497888) for a complete example of modifying list elements in a for loop. Just replace `li` with your list `dfs`. – Henry Ecker Oct 08 '21 at 16:00
  • that's not what I need or I don't know how to apply that logic. Thanks anyway. – Qthry Oct 08 '21 at 16:18

0 Answers0