0

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!

2
  • 2
    Why not dictionary? d = {'df33': read_xyT(path,33), 'df34': read_xyT(path,34)}. You can create it with a loop. Commented Sep 11, 2022 at 9:15
  • @Guy thanks for the hint, before I just know there is something called "dictionary", now I kind of understand what it is :) Commented Sep 11, 2022 at 13:24

1 Answer 1

1

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']

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much!! I am kind of new to python, or coding in general. I did it manually because I failed to find a solution by googling, but good that I decided to ask :) and learned a new method "dictionary" :D
I'm glad I could help! Best of luck on your journey!

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.