Home > Mobile >  Save multiple dataframes into the environment in Python
Save multiple dataframes into the environment in Python

Time:10-06

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")]

CodePudding user response:

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

CodePudding user response:

You can create for and check like below and create dict for match:

df = pd.DataFrame({'country_code': ['US','MX', 'CA', 'AU']})
codes = ['US', 'MX', 'CA', 'AU']
out = {code : df[df['country_code'].str.match(code)] for code in codes}

Output:

>>> out["US"]
     country_code
0    US

>>> type(out["US"])
pandas.core.frame.DataFrame


>>> out["CA"]
     country_code
2    CA
  • Related