【问题标题】:Split dataframe by rows and generate list of dataframes in python按行拆分数据帧并在python中生成数据帧列表
【发布时间】:2020-02-01 14:07:34
【问题描述】:

我有一个数据框:

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) 是一个数据帧。此外,我希望时间步长成为每个数据集中的索引。最后应该是这样的:

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

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

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

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

    【讨论】:

    • 你好 Mortz,你会改变什么以便将时间步长作为索引而不是常规索引,如上图所示?
    • 抱歉,我看不到图片——(企业访问限制)——但可能是df.set_index("Timestep", inplace=True)
    • 我已经试过了,但我似乎没有找到确切的位置,因为我们需要它来处理所有变量。您会将df.set_index("Timestep", inplace=True) 放在代码的什么位置?
    • 您可能应该编辑您的问题或询问一个新问题来更改索引 - 仅基于我的评论有点难以理解,其他人会错过这个问题,因为它在厘米
    【解决方案2】:

    目前在移动设备上无法测试,但您可以通过以下方式完成:

    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. 时间步长总是连续的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2019-06-16
      • 2020-12-14
      相关资源
      最近更新 更多