首页 > 解决方案 > 按行拆分数据帧并在python中生成数据帧列表

问题描述

我有一个数据框:

data = {'Timestep'      : [0,1,2,0,1,2,3,0,1],
        'Price'           : [5,7,3,5,7,10,8,4,8],
        'Time Remaining' : [10.0,10.0,10.0,15.0,15.0,15.0,15.0,12.0,12.0]}
df = pd.DataFrame(data, columns = ['Timestep','Price','Time Remaining'])

数据框

我想将数据帧转换为一个包含多个数据帧的列表,其中每个时间步长序列 (0-2,0-3,0-1) 是一个数据帧。此外,我希望时间步长成为每个数据集中的索引。最后应该是这样的:

包含多个数据框的列表

我有一个包含数千行和不规则序列的数据框,所以我想我必须遍历这些行。

有谁知道我该如何解决这个问题?

标签: pythonpandaslistdataframe

解决方案


据我了解-每当您Timestep达到 0时,您都需要一个新的 DataFrame-

这是你可以尝试的

#This will give you the location of all zeros [0, 3, 7]
zero_indices = list(df.loc[df.Timestep == 0].index)
#We append the number of rows to this to get the last dataframe [0, 3, 7, 9]
zero_indices.append(len(df))
#Then we get the ranges - tuples of consecutive entries in the above list [(0, 3), (3, 7), (7, 9)]
zero_ranges = [(zero_indices[i], zero_indices[i+1]) for i in range(len(zero_indices) - 1)]
#And then we extract the dataframes into a list
list_of_dfs = [df.loc[x[0]:x[1] - 1].copy(deep=True) for x in zero_ranges]

推荐阅读