quantik
quantik

Reputation: 816

Looping through and modifying list of variables

I have quite a few dataframes which I defined early in my script and I would like to iterate over them and modify them like so:

for df in [df_fap, df_spf, df_skin, ...]:
     df = df.filter(regex=(assay + r"[0-9]+"))

However this does not work. The values of the dataframes are not modified when the loop finishes. I stumbled upon this post which is slightly similar (except I define my variables beforehand) but it doesn't really offer a solution to my exact problem. Thanks!

Upvotes: 0

Views: 97

Answers (3)

Tomos Williams
Tomos Williams

Reputation: 2088

so you have your list of variables

[df_fap, df_spf, df_skin, ...]

when you loop you're creating a new variable

for df in [df_fap, df_spf, df_skin, ...]:
    df = value

each iteration (loop) of your for is reseting the value of df, meaning none of your variables will change

the answer khelwood gave means you'll redeclare all of your variables and apply the filter in one

df_fap, df_spf, df_skin, ... = [df_fap, df_spf, df_skin, ...]

try doing something like

a,b = ["apple","banana"]

in your console and khelwood's explaination will make sense

Upvotes: 1

khelwood
khelwood

Reputation: 59232

The looping variable df is in turn assigned each element of your list. If you reassign df, then you've made df refer to something else. It doesn't affect the list.

Reassigning the looping variable when iterating through a list doesn't alter the list, let alone altering the variables that were used to populate the list.

Try a list comprehension.

new_list = [df.filter(whatever) for df in (df_fap, df_spf, df_skin, ...)]

If you then also want to reassign your starting variables, you could use:

df_fap, df_spf, df_skin, ... = new_list

You could even do both those operations in one shot:

df_fap, df_spf, df_skin, ... = [df.filter(whatever) for df in (df_fap, df_spf, df_skin, ...)]

Upvotes: 2

Jerry Zhao
Jerry Zhao

Reputation: 194

Try

for i in range(len(df_list)):
    df_list[i] = df_list[i].filter(...)

Upvotes: 0

Related Questions