0

I have a variable mmmyy=Jul18 and want to create a dataframe in python using this variable named as df_Jul18. mmmyy is a dynamic variable for next month the df name will be df_Aug18.

Could anyone please help me achieving this. I tried my best but couldn't succeed.

1 Answers1

1

Don't create dynamically named variables

It is poor practice: makes your code intractable, clutters the namespace, removes the connection between related variables.

Use a dictionary instead

Usefully, Python provides an efficient method to provide labels for variables via hashable keys. The use of dict will make your life easier and make your code more readable. For example:

dfs = {}

mmmyy = 'Jul18'
dfs[mmmyy] = pd.DataFrame(columns=['col1', 'col2', 'col3'])

print(dfs)

{'Jul18': Empty DataFrame
          Columns: [col1, col2, col3]
          Index: []}

Then access your dataframe via dfs['Jul18'].

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Thanks a lot for your response and correcting me with the right approach. I will definitely use the dictionary in such scenarios. It helped me a lot. Cheers, keep rolling good stuff; highly appreciated! – Girish Arora Jul 30 '18 at 07:38