LMGagne
LMGagne

Reputation: 1706

Dynamically naming saved dataframes in loop

I'm attempting to use the GTab package to query Google Search trends data for every state in the US, but am having some trouble getting my loop to work.

For one state it's easy enough to do this, and new_query produces a dataframe.

t = gtab.GTAB()
t.set_options(pytrends_config={"geo": "US-NY", "timeframe": "2020-09-01 2020-10-01"})
query = t.new_query("weather")

To loop through I'm trying to use a dict to assign geo dynamically. However, I can't figure out how to do the same for the df name (query).

state_abbrevs = {
    'Alabama': 'AL',
    'Alaska': 'AK',
    'Arizona': 'AZ',
    'Arkansas': 'AR',
    'California': 'CA',
    'Colorado': 'CO',
    'Connecticut': 'CT',
    'Delaware': 'DE',
    'District of Columbia': 'DC',
    'Florida': 'FL',
    'Georgia': 'GA',
    'Guam': 'GU',
    'Hawaii': 'HI',
    'Idaho': 'ID',
    'Illinois': 'IL',
    'Indiana': 'IN',
    'Iowa': 'IA',
    'Kansas': 'KS',
    'Kentucky': 'KY',
    'Louisiana': 'LA',
    'Maine': 'ME',
    'Maryland': 'MD',
    'Massachusetts': 'MA',
    'Michigan': 'MI',
    'Minnesota': 'MN',
    'Mississippi': 'MS',
    'Missouri': 'MO',
    'Montana': 'MT',
    'Nebraska': 'NE',
    'Nevada': 'NV',
    'New Hampshire': 'NH',
    'New Jersey': 'NJ',
    'New Mexico': 'NM',
    'New York': 'NY',
    'North Carolina': 'NC',
    'North Dakota': 'ND',
    'Northern Mariana Islands':'MP',
    'Ohio': 'OH',
    'Oklahoma': 'OK',
    'Oregon': 'OR',
    'Pennsylvania': 'PA',
    'Puerto Rico': 'PR',
    'Rhode Island': 'RI',
    'South Carolina': 'SC',
    'South Dakota': 'SD',
    'Tennessee': 'TN',
    'Texas': 'TX',
    'Utah': 'UT',
    'Vermont': 'VT',
    'Virgin Islands': 'VI',
    'Virginia': 'VA',
    'Washington': 'WA',
    'Washington DC' : 'DC',
    'West Virginia': 'WV',
    'Wisconsin': 'WI',
    'Wyoming': 'WY'
}
for v in state_abbrevs.values():
    t = gtab.GTAB()
    t.set_options(pytrends_config={"geo": f"US-{v}", "timeframe": "2020-09-01 2020-10-01"})
    query = t.new_query("weather")

I've tried using an f string but that produces SyntaxError: can't assign to literal.

Upvotes: 0

Views: 65

Answers (1)

JAV
JAV

Reputation: 675

I used two answers from here. I think your best option is just storing the DataFrames in a dictionary but this should work to create your query_* variables.

query_dict = {}

for n, v in enumerate(state_abbrevs.values()):
    t = gtab.GTAB()
    t.set_options(pytrends_config={"geo": f"US-{v}", "timeframe": "2020-09-01 2020-10-01"})
    query = t.new_query("weather")
    key = "query_" + str(n)
    query_dict[key] = query

for k in query_dict.keys():
    exec("%s = query_dict['%s']" % (k,k))

Upvotes: 1

Related Questions