Python histogram by array

Метод numpy.histogram() в Python — гистограмма массива

Метод numpy.histogram() в Python вычисляет «гистограмму массива». Гистограмма — это графическое представление распределения данных. Это столбчатая диаграмма, где ось x представляет ячейки данных(интервалы), а ось y представляет количество точек данных в каждой ячейке.

Синтаксис

numpy . histogram ( arr , bins = 10 , range = None , normed = None , weights = None , density = None )

Аргументы

Функция np.histogram() принимает один обязательный аргумент в качестве параметра и имеет пять необязательных аргументов:

  1. arr: в этом аргументе передается массив. Массив является обязательным аргументом для возврата гистограммы.
  2. bins: это количество бинов. Десять хранятся в качестве бинов по умолчанию. Значение этого аргумента может быть последовательностью чисел, int или str. Если это int, то ширина бинов создается одинаково. Если это список, то значения ячеек меняются.
  3. range: это диапазон, в котором значения будут рассматриваться. Если значение превышает диапазон, то это значение не будет учитываться. Диапазон состоит из двух значений, начального и конечного, заключен в кортеж. Этот кортеж состоит из( start, end ) начального и конечного значений в диапазоне.
  4. normed: похож на аргумент density.
  5. weight: этот аргумент передается с массивом, состоящим из весов. Форма этого массива должна быть равна форме массива a. Аргумент weight нормализуется, если для параметра density задано значение True.
  6. density: если это True, то значение функции плотности вероятно. Если False, массив будет иметь количество выборок в каждой ячейке.

Возвращаемое значение numpy.histogram()

Метод возвращает два значения. Одно представляет собой массив значений гистограммы, а другое состоит из границ бинов.

Читайте также:  Call css in javascript

Источник

numpy.histogram#

Input data. The histogram is computed over the flattened array.

bins int or sequence of scalars or str, optional

If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform bin widths.

If bins is a string, it defines the method used to calculate the optimal bin width, as defined by histogram_bin_edges .

range (float, float), optional

The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()) . Values outside the range are ignored. The first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data.

weights array_like, optional

An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1.

density bool, optional

If False , the result will contain the number of samples in each bin. If True , the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function.

Returns : hist array

The values of the histogram. See density and weights for a description of the possible semantics.

bin_edges array of dtype float

Return the bin edges (length(hist)+1) .

All but the last (righthand-most) bin is half-open. In other words, if bins is:

then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3) . The last bin, however, is [3, 4] , which includes 4.

>>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3]) (array([0, 2, 1]), array([0, 1, 2, 3])) >>> np.histogram(np.arange(4), bins=np.arange(5), density=True) (array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) (array([1, 4, 1]), array([0, 1, 2, 3])) 
>>> a = np.arange(5) >>> hist, bin_edges = np.histogram(a, density=True) >>> hist array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]) >>> hist.sum() 2.4999999999999996 >>> np.sum(hist * np.diff(bin_edges)) 1.0 

Automated Bin Selection Methods example, using 2 peak random data with 2000 points:

>>> import matplotlib.pyplot as plt >>> rng = np.random.RandomState(10) # deterministic random data >>> a = np.hstack((rng.normal(size=1000), . rng.normal(loc=5, scale=2, size=1000))) >>> _ = plt.hist(a, bins='auto') # arguments are passed to np.histogram >>> plt.title("Histogram with 'auto' bins") Text(0.5, 1.0, "Histogram with 'auto' bins") >>> plt.show() 

Источник

NumPy Histogram: Understanding the np.histogram Function

NumPy Histogram Understanding the np.histogram Function Cover Image

In this tutorial, you’ll learn how to use the NumPy histogram function to calculate a histogram of a given dataset. A histogram shows the frequency of numerical data in bins of grouped ranges. By using NumPy to calculate histograms, you can easily calculate and access the frequencies (relative or absolute) of different values.

By the end of this tutorial, you’ll have learned:

  • How the NumPy histogram function works
  • How to customize the number and range of bins in the resulting histogram
  • How to return either absolute values or the probability density function of the bin

Understanding the NumPy Histogram Function

In this section, you’ll learn about the np.histogram() function and the various parameters and default arguments the function provides. The function has six different parameters, one of which is required. Let’s take a look at what the function looks like:

# Understanding the np.histogram() Function import numpy as np np.histogram(a, bins=10, range=None, normed=None, weights=None, density=None)

We can see that the function provides a number of different parameters. The table below breaks down the parameters and their default arguments:

Источник

Оцените статью