-1

Is there any way to construct a list of dataframes from a 1-dim dataframe or list? I thought apply would do the trick but it seems not to be the case. The job can be done easily by using a for loop but I wish to avoid that. More details down below.

This is the code I tried but it wouldn't work

pd.DataFrame([1,2,3,4,5]).apply(lambda x: pd.DataFrame([x]))

This is the code that would do the trick but for loop is what I wish to avoid at all cost, do run it so that you know what I actually try to achieve

list = [1,2,3,4,5]
j = []
for i in list:
    i = pd.DataFrame([i])
    j = j + [i]

In the project I work on, the thing I wish to do would be much more complex than just turning a element into a 1x1 dataframe but rather transforming it into a huge dataframe and eventually each of the dataframes generated would be put into a list, the only bottleneck is exactly this issue I described, thanks in advance.

1 Answers1

1

You can simplify and speed up your loop by using list comprehension which takes away the overhead of a for loop, here's a good read on it

Note: I renamed your list to lst since "list" is a reserved word in Python, don't use it as an variable

dfs = [pd.DataFrame([x]) for x in lst]

Now we can access each dataframe:

print(dfs[0])

   0
0  1

print(dfs[1])

   0
0  2
Erfan
  • 40,971
  • 8
  • 66
  • 78