Search code examples
pythonpandasf-string

Save multiple dataframes into the environment in Python


I have a similar problem with this question but the original question was to make multiple csv output. In my case, I am wondering if there's a way to make the multiple dataframe output into environment through a loop so I can carry on some data analysis.

us = df[df['country_code'].str.match("US")]
mx = df[df['country_code'].str.match("MX")]
ca = df[df['country_code'].str.match("CA")]
au = df[df['country_code'].str.match("AU")]

Solution

  • You could use the same code as the link posted, but save the different dfs into a dictionary:

    codes = ['US', 'MX', 'CA', 'AU']
    result_dict = {}
    for code in codes:
        temp = df.query(f'country_code.str.match("{code}")')
        result_dict[code] = temp