0

Im trying to automates process of creating dataframes as iam trying to do analysis of multiple spreadsheets in pandas. is there a way that a dataframe variable name can be auto-defined inside a for loop? in the example below, i defined 3 csv paths and i want to end up with 3 dataframes having names: df1 df2 df3

csvpath= ("/home/file1.csv","/home/file2.csv","/home/file3.csv")

for i in range (1,4):
    dfi=pd.read_csv(csvpath(i))
2
  • Just put them in a list... Commented May 5, 2020 at 3:42
  • how to do that? Commented May 5, 2020 at 3:46

2 Answers 2

2

Something like this should work...

csvpaths = ("/home/file1.csv", "/home/file2.csv", "/home/file3.csv")
dataframes = list()   # an empty list
for i in range (len(csvpaths)):
    dataframes.append(pd.read_csv(csvpath[i]))
Sign up to request clarification or add additional context in comments.

Comments

1

This is what you are trying to achieve. But this is not recommended.

csvpath= ("/home/file1.csv","/home/file2.csv","/home/file3.csv")

for i in range (1,4):
    globals()[f"df{i}"]=pd.read_csv(csvpath(i))

Instead use a list:

csvpath= ("/home/file1.csv","/home/file2.csv","/home/file3.csv")
dfs =[]
for i in range (1,4):
    dfs.append(pd.read_csv(csvpath(i)))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.