복붙노트

[PYTHON] scipy / numpy로 파이썬에서 데이터 비닝

PYTHON

scipy / numpy로 파이썬에서 데이터 비닝

미리 지정된 저장소에서 어레이의 평균을 취하는 더 효율적인 방법이 있습니까? 예를 들어 배열의 빈 시작 및 끝 위치에 해당하는 숫자 배열과 배열을 가지고 있으며 그 빈에서 평균을 취하고 싶습니까? 나는 아래 코드를 가지고 있지만 어떻게자를 수 있고 향상시킬 수 있는지 궁금합니다. 감사.

from scipy import *
from numpy import *

def get_bin_mean(a, b_start, b_end):
    ind_upper = nonzero(a >= b_start)[0]
    a_upper = a[ind_upper]
    a_range = a_upper[nonzero(a_upper < b_end)[0]]
    mean_val = mean(a_range)
    return mean_val


data = rand(100)
bins = linspace(0, 1, 10)
binned_data = []

n = 0
for n in range(0, len(bins)-1):
    b_start = bins[n]
    b_end = bins[n+1]
    binned_data.append(get_bin_mean(data, b_start, b_end))

print binned_data

해결법

  1. ==============================

    1.아마도 numpy.digitize ()를 사용하는 것이 더 빠르고 쉽습니다.

    아마도 numpy.digitize ()를 사용하는 것이 더 빠르고 쉽습니다.

    import numpy
    data = numpy.random.random(100)
    bins = numpy.linspace(0, 1, 10)
    digitized = numpy.digitize(data, bins)
    bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]
    

    numpy.histogram ()을 사용하면됩니다.

    bin_means = (numpy.histogram(data, bins, weights=data)[0] /
                 numpy.histogram(data, bins)[0])
    

    어느 쪽이 더 빠를지 스스로 시험해보십시오. :)

  2. ==============================

    2.Scipy (> = 0.11) 함수 scipy.stats.binned_statistic은 특히 위의 질문을 다룹니다.

    Scipy (> = 0.11) 함수 scipy.stats.binned_statistic은 특히 위의 질문을 다룹니다.

    이전 답변에서와 같은 예제의 경우, Scipy 솔루션은

    import numpy as np
    from scipy.stats import binned_statistic
    
    data = np.random.rand(100)
    bin_means = binned_statistic(data, data, bins=10, range=(0, 1))[0]
    
  3. ==============================

    3.이 스레드가 왜 괴롭혀 졌는지 확실하지 않습니다. 2014 년에 승인 된 답변이 있는데, 이는 훨씬 더 빨라야합니다.

    이 스레드가 왜 괴롭혀 졌는지 확실하지 않습니다. 2014 년에 승인 된 답변이 있는데, 이는 훨씬 더 빨라야합니다.

    import numpy as np
    
    data = np.random.rand(100)
    bins = 10
    slices = np.linspace(0, 100, bins+1, True).astype(np.int)
    counts = np.diff(slices)
    
    mean = np.add.reduceat(data, slices[:-1]) / counts
    print mean
    
  4. ==============================

    4.numpy_indexed 패키지 (면책 조항 : 저는 저자입니다)에는이 유형의 작업을 효율적으로 수행하는 기능이 포함되어 있습니다.

    numpy_indexed 패키지 (면책 조항 : 저는 저자입니다)에는이 유형의 작업을 효율적으로 수행하는 기능이 포함되어 있습니다.

    import numpy_indexed as npi
    print(npi.group_by(np.digitize(data, bins)).mean(data))
    

    이것은 이전에 게시 한 솔루션과 본질적으로 동일한 솔루션입니다. 하지만 지금 테스트와 모든 좋은 인터페이스에 싸여 :)

  5. ==============================

    5.내가 추가하고 또한 질문에 대답 histogram2d python을 사용하여 평균 bin 값을 찾을 수있는 특별히 데이터의 하나 이상의 세트에 대한 bidimensional binned 통계를 계산하도록 설계된 기능을 가지고

    내가 추가하고 또한 질문에 대답 histogram2d python을 사용하여 평균 bin 값을 찾을 수있는 특별히 데이터의 하나 이상의 세트에 대한 bidimensional binned 통계를 계산하도록 설계된 기능을 가지고

    import numpy as np
    from scipy.stats import binned_statistic_2d
    
    x = np.random.rand(100)
    y = np.random.rand(100)
    values = np.random.rand(100)
    bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
    

    scipy.stats.binned_statistic_2d 함수는 상위 차원 데이터 세트에 대해이 함수를 일반화 한 것입니다

  6. from https://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy by cc-by-sa and MIT license