0
table_name = []
counter=0
for year in ['2017', '2018', '2019']:
    table_name.append(f'temp_df_{year}')
    print(table_name[counter])
    table_name[counter] = pd.merge(table1, table2.loc[table2.loc[:, 'year'] == year, :], left_on='col1', right_on='col1', how='left')
    counter += 1

temp_df_2017

The print statement outputs are correct: temp_df_2017, temp_df_2018, temp_df_2019

However, when I try to see what's in temp_df_2017, I get an error: name 'temp_df_2017' is not defined

I would like to create those three tables. How can I make this work?

PS: ['2017', '2018', '2019'] list will vary. It can be a list of quarters. That's why I want to do this in a loop, instead of using the merge statement 3x.

1
  • temp_df_2017 is a string - obviously it is not defined. Commented Feb 4, 2020 at 3:39

1 Answer 1

1

I think the easiest/most practical approach would be to create a dictionary to store names/df.

import pandas as pd
import numpy as np

# Create dummy data
data = np.arange(9).reshape(3,3)
df = pd.DataFrame(data, columns=['a', 'b', 'c'])

df
Out:
    a   b   c
0   0   1   2
1   3   4   5
2   6   7   8

df_year_names = ['2017', '2018', '2019']
dict_of_dfs = {}
for year in df_year_names:
    df_name = f'some_name_year_{year}'
    dict_of_dfs[df_name] = df    

dict_of_dfs.keys()
Out:
dict_keys(['some_name_year_2017', 'some_name_year_2018', 'some_name_year_2019'])

Then to access a particular year:

dict_of_dfs['some_name_year_2018']
Out:
    a   b   c
0   0   1   2
1   3   4   5
2   6   7   8
Sign up to request clarification or add additional context in comments.

Comments

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.