按行拆分数据帧并在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'])

http://img2.mukewang.com/62a844050001bee103760321.jpg

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

http://img.mukewang.com/62a844160001f0cb06560352.jpg

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

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


慕哥6287543
浏览 197回答 2
2回答

梵蒂冈之花

据我了解-每当您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 listlist_of_dfs = [df.loc[x[0]:x[1] - 1].copy(deep=True) for x in zero_ranges]

慕莱坞森

现在在移动设备上无法对此进行测试,但您可以通过以下方式完成:current_sequence_index = -1sequences = []for __, row in data.iterrows():    if row.Timestep == 0:        sequences.append(pd.DataFrame())        current_sequence_index += 1    sequences[current_sequence_index].append(row, ignore_index=True)   本质上,这将遍历您的数据并在 Timestep 为 0 时生成一个新的 DataFrame。此解决方案有一些假设:1. Timestep 的开始始终为 0。 2. Timesteps 始终是顺序的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python