NumPy 重复数据与去重

在数理统计分析中,需要提前将重复数据剔除,在NumPy中,可以通过unique 函数找到数组中的唯一值并返回已排序的结果。

数组内数据去重。(unique(a))

a = np.array(['red','blue','yellow','red','red','white'])
print("原数组:",a)
print("去重后的数组:",np.uni
#Output
#原数组: ['red' 'blue' 'yellow' 'red' 'red' 'white']
#去重后的数组: ['blue' 'red' 'white' 'yellow']

统计分析中有时候需要把一个数据重复若干次,使用tile和repeat函数即可实现此功能。

  • tile函数的格式:np.tile(A, reps)

其中,参数A表示要重复的数组,reps表示重复次数。

  • repeat函数的格式:np.repeat(A, reps, axis = None)

其中, “a”: 是需要重复的数组元素,“repeats”: 是重复次数, “axis”: 指定沿着哪个轴进行重复,axis = 0表示按行进行元素重复;axis = 1表示按列进行元素重复。

#使用tile 函数实现数据重复。
kk = np.array([1,2,3])
print(kk)
ll = np.tile(kk,3) #将kk数组重复三次
print(ll)
#Output
#[1 2 3]
#[1 2 3 1 2 3 1 2 3]
#使用repeat 函数实现数据重复。
kk = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(kk)
print('------------')
# ll = np.tile(kk,3) #将kk数组重复三次
# print(ll)
ll = np.repeat(kk,2,axis=1)
print(ll)
print('------------')
ss = np.repeat(kk,2,axis=0)
print(ss)
#Output
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
# ------------
# [[1 1 2 2 3 3]  #按列进行重复
#  [4 4 5 5 6 6]
#  [7 7 8 8 9 9]]
# ------------
# [[1 2 3]        #按行进行重复
#  [1 2 3]
#  [4 5 6]
#  [4 5 6]
#  [7 8 9]
#  [7 8 9]]

猜你喜欢

转载自blog.csdn.net/chenjh027/article/details/127953378