📜  如何计算 NumPy 数组中唯一值的频率?

📅  最后修改于: 2022-05-13 01:55:44.647000             🧑  作者: Mango

如何计算 NumPy 数组中唯一值的频率?

让我们看看如何计算 NumPy 数组中唯一值的频率。 Python 的 numpy 库提供了一个numpy.unique()函数来查找唯一元素及其在 numpy 数组中的相应频率。

现在,让我们看一些例子:

示例 1:

Python3
# import library
import numpy as np
  
ini_array = np.array([10, 20, 5,
                      10, 8, 20,
                      8, 9])
  
# Get a tuple of unique values 
# and their frequency in
# numpy array
unique, frequency = np.unique(ini_array, 
                              return_counts = True)
# print unique values array
print("Unique Values:", 
      unique)
  
# print frequency array
print("Frequency Values:",
      frequency)


Python3
# import library
import numpy as np
  
# create a 1d-array
ini_array = np.array([10, 20, 5,
                    10, 8, 20,
                    8, 9])
  
# Get a tuple of unique values 
# amnd their frequency 
# in numpy array
unique, frequency = np.unique(ini_array,
                              return_counts = True) 
  
# convert both into one numpy array
count = np.asarray((unique, frequency ))
  
print("The values and their frequency are:\n",
     count)


Python3
# import library
import numpy as np
  
# create a 1d-array
ini_array = np.array([10, 20, 5,
                      10, 8, 20,
                      8, 9])
  
# Get a tuple of unique values 
# and their frequency in
# numpy array
unique, frequency = np.unique(ini_array, 
                              return_counts = True) 
  
# convert both into one numpy array 
# and then transpose it
count = np.asarray((unique,frequency )).T
  
print("The values and their frequency are in transpose form:\n",
     count)


输出:

Unique Values: [ 5  8  9 10 20]
Frequency Values: [1 2 1 2 2]

示例 2:

Python3

# import library
import numpy as np
  
# create a 1d-array
ini_array = np.array([10, 20, 5,
                    10, 8, 20,
                    8, 9])
  
# Get a tuple of unique values 
# amnd their frequency 
# in numpy array
unique, frequency = np.unique(ini_array,
                              return_counts = True) 
  
# convert both into one numpy array
count = np.asarray((unique, frequency ))
  
print("The values and their frequency are:\n",
     count)

输出:

The values and their frequency are:
[[ 5  8  9 10 20]
[ 1  2  1  2  2]]

示例 3:

Python3

# import library
import numpy as np
  
# create a 1d-array
ini_array = np.array([10, 20, 5,
                      10, 8, 20,
                      8, 9])
  
# Get a tuple of unique values 
# and their frequency in
# numpy array
unique, frequency = np.unique(ini_array, 
                              return_counts = True) 
  
# convert both into one numpy array 
# and then transpose it
count = np.asarray((unique,frequency )).T
  
print("The values and their frequency are in transpose form:\n",
     count)

输出:

The values and their frequency are in transpose form:
[[ 5  1]
[ 8  2]
[ 9  1]
[10  2]
[20  2]]