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