how to create a loop and save the data array variable individually?

Question:

I write a helper function read_xyT to read all .csv files in a directory and output them into a pandas DataFrame. Since there are lots for such directories and I want to save them into individual variables (or maybe some better solutions?)

what I do now is

path = r'./data/T-600s'
df33 = read_xyT(path,33)
df34 = read_xyT(path,34)
df35 = read_xyT(path,35)
df36 = read_xyT(path,36)
...

There is in total 60 folders… I wonder if there is a smarter way to do it more efficiently? i.e.

subdirectoynames = np.arange(34,50) # the helper function take 'path' as input
variablenames = alistforfilenames
for v,f in (variablenames, subdirectorynames):
  dfxx = read_xyT(path,yy)

then I’ll have the saved individual variables such as df37, df38, df39, …

Or is there a better way to do it?

Thank you in advance!

Asked By: Ann

||

Answers:

You can use a dict comprehension:

df_dict = {f'df{idx}': read_xyT(path, idx) for idx in subdirectorynames}

This creates a dictionary where you can access the dataframes using e.g. df_dict['df33']

Answered By: code-lukas
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.