jyjyjyjyjyjjyjyj
jyjyjyjyjyjjyjyj

Reputation: 59

how can i make pandas dataframe objects using for loop in python

I want to create multiple pandas data frames df1,df2,df3,... from multiple files file1.xlsx, file2.xlsx ... using for loop

filenames = {'file1.xlsx','file2.xlsx','file3.xlsx','file4.xlsx','file5.xlsx'}

for i in range(len(filenames)):
    df+str(i) = pd.read.excel(filenames[i])

and get the syntax error 'can't assign to operator' how can I solve this problem?

Upvotes: 0

Views: 51

Answers (2)

JQadrad
JQadrad

Reputation: 541

Could you try something like this? Use exec to assign the value to the variable?

filenames = ['file1.xlsx','file2.xlsx','file3.xlsx','file4.xlsx','file5.xlsx']

for fname in filenames:
    dfname = fname.split('.')[0]
    df = pd.read_excel(fname)
    exec("%s=%s" % (dfname , df))

Upvotes: 0

BENY
BENY

Reputation: 323376

Try locals but not recommend

filenames = {'file1.xlsx','file2.xlsx','file3.xlsx','file4.xlsx','file5.xlsx'}
variables = locals()
for i in range(len(filenames)):
   variables["df{0}".format(i)]  = pd.read.excel(filenames[i])

We usually save it into dict

filenames = {'file1.xlsx','file2.xlsx','file3.xlsx','file4.xlsx','file5.xlsx'}
d={'df'+str(i) :  pd.read.excel(filenames[i]) for i in range(len(filenames))}

Upvotes: 1

Related Questions