itsource

팬더와 함께 기둥에 비닝하기

mycopycode 2023. 6. 16. 21:44
반응형

팬더와 함께 기둥에 비닝하기

숫자 값이 있는 데이터 프레임 열이 있습니다.

df['percentage'].head()
46.5
44.2
100.0
42.12

을 빈 카운트로 표시합니다.

bins = [0, 1, 5, 10, 25, 50, 100]

카운트가 있는 빈으로 결과를 가져오려면 어떻게 해야 합니까?

[0, 1] bin amount
[1, 5] etc
[5, 10] etc
...

다음을 사용할 수 있습니다.

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

또는:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...그 다음 또는 및 집계:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

기본적으로cut돌아온다categorical.

Series와 같은 방법Series.value_counts()에서는 데이터에 일부 범주가 없는 경우에도 범주형 연산을 포함하여 모든 범주를 사용합니다.

속도 향상을 위해 Numba 모듈을 사용합니다.

대규모 데이터셋(500k 이상)에서는pd.cut데이터 바인딩의 경우 속도가 상당히 느릴 수 있습니다.

저는 저스트 인 타임 컴파일로 Numba에서 제 기능을 작성했는데, 이는 대략 6배 더 빠릅니다.

from numba import njit

@njit
def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
        else:
            bins[idx] = 7

    return bins
cut(df['percentage'].to_numpy())

# array([5., 5., 7., 5.])

선택 사항: 빈에 문자열로 매핑할 수도 있습니다.

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

속도 비교:

# Create a dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)

dfbig.shape

# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())

# 38 ms ± 616 µs per loop (mean ± standard deviation of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± standard deviation of 7 runs, 10 loops each)

우리는 또한 사용할 수 있습니다.np.select:

bins = [0, 1, 5, 10, 25, 50, 100]
df['groups'] = (np.select([df['percentage'].between(i, j, inclusive='right') 
                           for i,j in zip(bins, bins[1:])], 
                          [1, 2, 3, 4, 5, 6]))

출력:

   percentage  groups
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

Numpy를 사용한 편리하고 빠른 옵션

np.digitize는 편리하고 빠른 옵션입니다.

import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [1,2,3,4,5]})
df['y'] = np.digitize(df['x'], bins=[3,5]) # convert column to bin

print(df)

돌아온다

   x  y
0  1  0
1  2  0
2  3  1
3  4  1
4  5  2

언급URL : https://stackoverflow.com/questions/45273731/binning-a-column-with-pandas

반응형