如何将这些类型的while循环结果保存到python中的多个数据帧中?

时间:2019-11-05 10:44:49

标签: python numpy dataframe while-loop

这是我的示例代码:

from window_slider import Slider
import numpy
list = numpy.array([0, 1, 2, 3, 4, 5, 6, 7 ,8])
bucket_size = 3
overlap_count = 0
slider = Slider(bucket_size,overlap_count)
slider.fit(list)       
while True:
    window_data = slider.slide()
    print(window_data)
    if slider.reached_end_of_list(): break

这显示了我的输出:

[0 1 2]
[3 4 5]
[6 7 8]

如果我试图将其保存在数据帧中,它将仅保存numpy数组的最后一个值[6,7和8]。我想将它们全部保存在不同的数据框中,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

尝试使用字典:

d = {}
c = 0
while True:
    c += 1
    window_data = slider.slide()
    d['df%s'%c] = window_data
    if slider.reached_end_of_list(): break

毕竟,只需使用d['df1']d['df2']等来进行访问,如果要像df1df2这样直接访问它们,请添加在代码末尾的下面一行:

locals().update(d)

然后df1df2将起作用。

答案 1 :(得分:0)

您可以使用列表将其存储在列表列表中:

from window_slider import Slider
import numpy
import pandas as pd
list = numpy.array([0, 1, 2, 3, 4, 5, 6, 7 ,8])
bucket_size = 3
overlap_count = 0
slider = Slider(bucket_size,overlap_count)
slider.fit(list) 

#Master list which consists of all the lists of arrays
output_list = []      
while True:
    window_data = slider.slide()
    #Convert the window_data array to a list
    output_df_list = window_data.tolist()
    #Append the "output_df_list" to the master list "output_list"
    output_list.append(output_df_list)
    print(window_data)
    if slider.reached_end_of_list(): break

输出:

print(output_list)
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]