0

What is the best practice to loop this?

I want to filter and dynamically create new DFs

df_aus19 = df_mat.loc[(df_temp['Year'] == 2020 ) & (df_mat['Country'] == 'AUS')]
df_aus20 = df_mat.loc[(df_temp['Year'] == 2020 ) & (df_mat['Country'] == 'AUS')]
df_aus21 = df_mat.loc[(df_temp['Year'] == 2021 ) & (df_mat['Country'] == 'AUS')]
df_aus22 = df_mat.loc[(df_temp['Year'] == 2022 ) & (df_mat['Country'] == 'AUS')]
df_aus23 = df_mat.loc[(df_temp['Year'] == 2023 ) & (df_mat['Country'] == 'AUS')]

AS per code

1
  • In my answer I am assuming the first filter should be 2019 as implied by the naming of the corresponding variable. Commented Jun 4, 2019 at 13:12

2 Answers 2

1

A more pythonic way to solve your problem than by loops and dynamically creating global variables would be a list comprehension:

years = list(range(2019, 2024))
df_aus_list = [df_mat.loc[(df_temp['Year'] == i) & (df_mat['Country'] == 'AUS')] for i in years]

If you really need to produce the same result as your code you could dynamically create new global variables like so:

years = list(range(2019, 2024))
for i in years:
    globals()["df_aus"+str(i % 100)] = df_mat.loc[(df_temp['Year'] == i ) & (df_mat['Country'] == 'AUS')]
Sign up to request clarification or add additional context in comments.

Comments

1

Don't. Just don't. When you find yourself ready to dynamically create new variables, just refrain: it is hard to obtain and harder to maintain. Just use containers like dictionaries or lists.

And the common way to get that in pandas is group_by:

dfs = dict()
for (year, country), sub in df.groupby(['Year', 'Country']):
  # if 2020 <= year <= 2023 and county == 'AUS':     # filter optionaly
      dfs[(year, country)] = sub

You can then get the dataframe for AUS and 2021 as dfs[(2021, 'AUS')]

1 Comment

Nice trick with dfs..so each Value corresponds to dataframe referenced by the Key (2019, AUS')...etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.