【问题标题】:How to split a Pandas DataFrame into multiple DataFrame by the sum of a certain value?如何通过某个值的总和将 Pandas DataFrame 拆分为多个 DataFrame?
【发布时间】:2020-07-23 05:39:59
【问题描述】:

我有一个看起来像这样的 DataFrame:

    Name      Count
0   John      0.25
1   Adam      0.75
2   Michael   1.5
3   Jane      0.8
4   Anna      2.0
5   Sarah     0.25

我的目标是根据限制值将此 DataFrame 拆分为多个 DataFrame。 对于此示例,限制值为 3 - 因此结果如下所示:

    Name      Count
0   John      0.25
1   Adam      0.75
2   Michael   1.5


   Name      Count
0  Jane      0.8
1  Anna      2.0

   Name      Count
0  Sarah     0.25

关键是在每个新的 DataFrame 中,计数的总和接近极限值,但没有超过它(即 Jane 在第二个 DataFrame 中,因为如果她包含在第一个 DataFrame 中,总和将为3.3,超过了3)的极限值。

我相信 .iterrows 可以做到这一点,但这相当重/慢,所以寻找另一种解决方案。

【问题讨论】:

  • 你能发布一个可重现的例子,这样使用起来会更容易吗?
  • 你可以使用pd.read_clipboard()@UGuntupalli

标签: python pandas dataframe


【解决方案1】:

我们可以,

LIMIT = 3
assert df['Count'].le(LIMIT).all()

groups = []
sum = 0
group = 0

for val in df['Count']:
    sum += val
    if sum > LIMIT:
        group += 1
        sum = val
    groups.append(group)
    
my_dict = {f'Group {i}' : group.reset_index(drop=True) 
           for i, group in df.groupby(groups)}
#print(my_dict['Group 0'])

【讨论】:

    【解决方案2】:

    为了加快速度,我们可以使用numba,它是及时编译(JIT),效率很高:

    函数由我的另一个answer 调整

    from numba import njit
    import numpy as np
    
    @njit
    def cumsum_reset(array, limit):
        total = 0
        counter = 0
        groups = np.empty(array.shape[0])
        
        for idx, i in enumerate(array):
            total += i
            if total >= limit:
                total = 0
                total += i
                counter += 1
                groups[idx] = counter
            else:
                groups[idx] = counter
    
        return groups
    
    groups = cumsum_reset(df['Count'].to_numpy(), 3)
    
    for _, grp in df.groupby(groups):
        print(grp)
    
          Name  Count
    0     John   0.25
    1     Adam   0.75
    2  Michael   1.50
       Name  Count
    3  Jane    0.8
    4  Anna    2.0
        Name  Count
    5  Sarah   0.25
    

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 2020-01-15
      • 2019-11-30
      • 1970-01-01
      • 2020-09-13
      • 2020-03-02
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多