为了账号安全,请及时绑定邮箱和手机立即绑定

按行拆分数据帧并在python中生成数据帧列表

按行拆分数据帧并在python中生成数据帧列表

慕哥6287543 2022-06-14 16:16:48
我有一个数据框: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) 是一个数据帧。此外,我希望时间步长成为每个数据集中的索引。最后应该是这样的:我有一个包含数千行和不规则序列的数据框,所以我想我必须遍历这些行。有谁知道我该如何解决这个问题?
查看完整描述

2 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

据我了解-每当您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]


查看完整回答
反对 回复 2022-06-14
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

现在在移动设备上无法对此进行测试,但您可以通过以下方式完成:


current_sequence_index = -1

sequences = []

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 始终是顺序的。


查看完整回答
反对 回复 2022-06-14
  • 2 回答
  • 0 关注
  • 196 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号