Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a loop to generate variable names in Python [duplicate]

I'm trying to import datasets which have the following filenames (phone1, phone2, etc)

df1 = pd.read_csv(r'C:\Users\...\phone1.csv')
df2 = pd.read_csv(r'C:\Users\...\phone2.csv')
df3 = pd.read_csv(r'C:\Users\...\phone3.csv')
df4 = pd.read_csv(r'C:\Users\...\phone4.csv')
df5 = pd.read_csv(r'C:\Users\...\phone5.csv')
df6 = pd.read_csv(r'C:\Users\...\phone6.csv')

I tried the following code

for i in range(1, 7):
    'df'+i = pd.read_csv(r'C:\Users\siddhn\Desktop\phone'+str(i)+'.csv', engine = 'python')

But I get an error saying that cannot assign to operator

How to import the datasets using a loop.?

like image 464
siiddd Avatar asked Aug 09 '26 22:08

siiddd


1 Answers

As @TimRoberts mentioned, you should use a list or a dictto store your dataframes but if you really want to have variable df1, df2, ..., df6, you can use locals() or globals():

for i in range(1, 7):
    locals()[f'df{i}'] = pd.read_csv(fr'C:\Users\siddhn\Desktop\phone{i}.csv')

print(df1)
print(df2)
like image 185
Corralien Avatar answered Aug 12 '26 12:08

Corralien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!