Home > Back-end >  Create DataFrame Variables Inside For Loop / Group DataFrames
Create DataFrame Variables Inside For Loop / Group DataFrames

Time:10-26

How can I store each dataframes into a unique variable (ie; df1, df2, df3,...)? Is it possible to create new variables inside the for loop? So, it creates variables only if it requires.

For example, if there are 5 dataframes created, each of them will be stores in df1, df2, df3, df4, and df5. No extra variables will be created.

import numpy as np
import pandas as pd

# Selects random number from 3 to 10
three_to_ten = np.random.randint(3,10)

# Random number of loops from 3 to 10
for x in range(0,three_to_ten):

  # Creates random number of dataframe with random length
  data = np.random.randint(three_to_ten, size= three_to_ten)
  df = pd.DataFrame(data, columns=['numbers'])

  print (df)

CodePudding user response:

As mentioned in the comments, you can use a dict:

import numpy as np
import pandas as pd

three_to_ten = np.random.randint(3, 10)
dataframes = {}

for x in range(0, three_to_ten):
  data = np.random.randint(three_to_ten, size=three_to_ten)
  df = pd.DataFrame(data, columns=['numbers'])
  dataframes[f'df{x}'] = df

print(dataframes)
  • Related