1

I am a beginner of Python.
Now, I have files "Pref1" and "Pref2".
I would like to read files and define data frame's names with for-loop fuction (there are so many files).
I tried below.

for i in [1,2]:
    f"df{i} = pd.read_excel('Pref{i}.xlsx', sheet_name= 'Sheet2').dropna(axis=0)

However, codes do not work. If you have good ideas, please tell me. Thank you.

1
  • for i in range(1,2): Commented Jul 16, 2022 at 9:37

1 Answer 1

2

Use a dictionary to save your data frames with preferred names and get them later

CODE

import pandas as pd

df_dict = {}

for i in [1, 2]:
    df_dict["df"+str(i)] = pd.read_excel(f'Pref{i}.xlsx', sheet_name='Sheet2').dropna(axis=0)

df1 = df_dict["df1"]
df2 = df_dict["df2"]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much!! The code works!! But is it difficult to save data and name at once?
A dictionary or List is the only way for achieving this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.