0

I want to generate multiple new dataframe using for loop, but my code didn't work.

id   col
a      4
b      5
c      6

code

l = [i for i in range(1,4)]

for i in l:
    df['col'+str(i)] = df['col']*i

It returns me a new df with 3 new columns. But the results I need are 3 new dataframes named df1, df2 and df3 with new column separately.

How can I generate multiple new dataframe using a loop?

Jiayu Zhang
  • 719
  • 7
  • 22

1 Answers1

0

From your example, it's not entirely clear what you want your DataFrames to contain.

So, here's some code that creates 3 DataFrames called DF1, DF2, & DF3.

Each with 1-4*idx as the sole column.

Please clarify if you wanted something else.

import pandas as pd

# Need to track the created DataFrames in some way. Using a dict here.
df_dict = dict()
for idx in [1, 2, 3]: #  Using list 1,2,3, but could be changed back to l or range().
    df_dict['DF'+str(idx)] = pd.DataFrame([1, 2, 3, 4])*idx

# This adds the key/value pairs as variables to the __locals__ dict. 
# Generally not best practice.
locals().update(df_dict)

print(DF1)
print(DF2)
print(DF3)

In the above code, DFx is created in a dictionary to trace their creation, and then I add them to the locals dictionary. I would not write code like this.

My recommendation is to just use the generated dictionary (df_dict) directly.

Also, you can use multilevel/multidimensional DataFrames to probably solve whatever problem you would be using this for idx in range(x) for. If you provide more detail I may be able to suggest better methods.

Cheers!

jayreed1
  • 152
  • 2
  • 8