0

I want to create a Pandas dataframe for each of a list of pickle files.

If I use this code:

dfs = [pd.read_pickle(file) for file in DATA_PROCESSED.iterdir()]

I will get a list, but I want also to make a correspondence between filename and dataframe name. In this case I will get only dfs[0] e.g.

Could you help me?

Hugo
  • 1,558
  • 12
  • 35
  • 68

1 Answers1

1

You could use a dictionary comprehension instead of a list comprehension. You can strip the extension name from the dictionary key for easier access later using .strip('.pkl'), replacing .pkl with whatever extension you are using.

dfs = {file.strip('.pkl'):pd.read_pickle(file) for file in DATA_PROCESSED.iterdir()}

Then you can access each using normal dictionary syntax:

dfs['filename']
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • Thank you. Is it possible to have individual dataframe, without belonging to a list or dict? – Hugo Aug 04 '18 at 16:42
  • Not safely, as far as I know, short of following the advice in [this answer](https://stackoverflow.com/questions/18090672/convert-dictionary-entries-into-variables-python/36059129#36059129) (which I *do not* recommend) – sacuL Aug 04 '18 at 16:46