разделить фрейм данных - PullRequest
       15

разделить фрейм данных

2 голосов
/ 28 октября 2019

печать (df)

  A  B  
  0  10  
  1  30  
  2  50  
  3  20  
  4  10  
  5  30

AB
0 10
1 30

AB

2 50

AB

3 20
4 10
5 30

Ответы [ 2 ]

3 голосов
/ 28 октября 2019

Вы можете использовать pd.cut в совокупной сумме столбца B:

th = 50

# find the cumulative sum of B 
cumsum = df.B.cumsum()

# create the bins with spacing of th (threshold)
bins = list(range(0, cumsum.max() + 1, th))

# group by (split by) the bins
groups = pd.cut(cumsum, bins)

for key, group in df.groupby(groups):
    print(group)
    print()

Выход

   A   B
0  0  10
1  1  30

   A   B
2  2  50

   A   B
3  3  20
4  4  10
5  5  30
1 голос
/ 28 октября 2019

Вот метод, использующий numba для ускорения нашего for loop:

Мы проверяем, когда наш предел достигнут, сбрасываем счет total и назначаем новый group:

from numba import njit

@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 >= 50 or array[idx-1] == 50:
            counter += 1
            groups[idx] = counter
            total = 0
        else:
            groups[idx] = counter

    return groups

grps = cumsum_reset(df['B'].to_numpy(), 50)

for _, grp in df.groupby(grps):
    print(grp, '\n')

Выход

   A   B
0  0  10
1  1  30 

   A   B
2  2  50 

   A   B
3  3  20
4  4  10
5  5  30

Время :

# create dataframe of 600k rows
dfbig = pd.concat([df]*100000, ignore_index=True)
dfbig.shape

(600000, 2)

# Erfan
%%timeit
cumsum_reset(dfbig['B'].to_numpy(), 50)

4.25 ms ± 46.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# Daniel Mesejo
def daniel_mesejo(th, column):
    cumsum = column.cumsum()
    bins = list(range(0, cumsum.max() + 1, th))
    groups = pd.cut(cumsum, bins)

    return groups

%%timeit
daniel_mesejo(50, dfbig['B'])

10.3 s ± 2.17 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

Заключение * * * * * * * numba для цикла в 47000 раз быстрее.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...