0

I am trying to run a while loop in python and I want to name my dataframes dynamically based on the integration number. Below is the code I have -

while i < count_keys
key_curr = keys[%i]
temp_%i=mod.copy()
temp_%i.groupby([key_curr]).agg({'iclic_id':"count"})
temp_%i.rename(columns={'count':'CT_'key_curr})

I want to know if this way of referencing "%i" is the correct way or is there any other way to reference "i". Thanks for the help!

  • I suggest you store the dataframes in a dictionary. The key would be the dynamically generated name (as a string) and the value would be the dataframe. Trying to create dynamic variable names is rarely worth the effort. – cdarke Apr 24 '17 at 08:08
  • Check the indent of your code – Dmitry Apr 24 '17 at 08:10
  • Possible duplicate of [How can you dynamically create variables via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-via-a-while-loop) – FLab Apr 24 '17 at 08:25

2 Answers2

1

Not sure if i got what you want but my guess is you want to dynamically create variables:

while i < count_keys:
    key_curr = keys[i]
    globals()['temp_%i' % i] = mod.copy()
    globals()['temp_%i' % i].groupby([key_curr]).agg({'iclic_id':"count"})
    globals()['temp_%i' % i].rename(columns={'count':'CT_%i' % key_curr})
zipa
  • 27,316
  • 6
  • 40
  • 58
0

dynamic variable names are not recommended. instead, use dictionary to store your data.

for example:

my_data = {}
for i, key_curr in enumerate(keys):
    my_data['temp_%d' % i] = mod.copy().groupby([key_curr]).agg({'iclic_id':"count"}).rename(columns={'iclic_id':'CT_' + key_curr})
print my_data.values()
Yaron Neuman
  • 102
  • 1
  • 2