简体   繁体   中英

Can I use apply() or anyting else on a 1-dim dataframe to construct a list of dataframes?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM