-1

I want to create n variables by splitting a dataframe of n rows. The idea is something like below.

for i in range(len(my_df)):
    my_new_df_i = my_df[i]
  • 2
    Don't create variable variables, it is terrible idea 99% of the time. Use a list/dictionary instead. Or in your case, just stick with df. – matszwecja May 04 '22 at 09:25
  • Does this answer your question? [How can you dynamically create variables?](https://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables) – luk2302 May 04 '22 at 09:32

1 Answers1

0

As someone already said in comments, this is not what you should do, expecially if your goal is to operate with each row of a dataframe.

You can iterate the rows of the df with DataFrame.iterrows() (https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iterrows.html) and do what you want, but don't save each of them in a variable, it would introduce big memory problems and overhead.

Anyway, just for the purpose of learning, you can create variables using iterativelly in a loop using indexes using locals() or globals() functions, which return a dictionary of the current variables that can be modified:

>>> l = [a, b, c]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> l = ["a", "b", "c"]
>>> for i, el in enumerate(l):
...     locals()[el] = i
... 
>>> a
0
>>> b
1
>>> c
2
>>>