Home > Mobile >  creating new df after every iteration (pandas, python)
creating new df after every iteration (pandas, python)

Time:10-14

is it possible to create a new df after every iteration? with [i] being the iteration, it should generate df0, df1, df2, etc.. to the MAX NUMBER range as presented in the example:

for i in range(MAX_NUMBER   1):
   df[i] = pd.read_csv(f"C:/Users/Desktop/{i}.csv")

the original codes are functions that loop multiple times. however, for simplicity, i've use read.csv for the example.

kindly advise. Many thanks

CodePudding user response:

Try creating array and append df as you progress through for loop. like this,

df = []
for i in range(MAX_NUMBER   1):
    df.append(pd.read_csv(f"C:/Users/Desktop/{i}.csv"))

and when you need to access, you can use index like df[0], df[1].

CodePudding user response:

Read file and assign it to a dictionary key with key being the name of dataframe as follows:

dfs = {}
for i in range(MAX_NUMBER   1):
   dfs[f'df{i}'] = pd.read_csv(f"C:/Users/Desktop/{i}.csv")

Then you can access each df by its name:

dfs['df0']
  • Related