欢迎来到RankFan的Blogs

扩大
缩小

Numpy

生成储存器:

unique

可以起到去重的作用

random

生成随机数

error = np.squeeze(np.random.randn(200, 1))

Reshape

a = np.arange(6).reshape((3, 2))
np.reshape(a, (3,-1))  # 变成3行的,自己计算列数
  • theta.reshape(-1) 变成一维度。

array拼接

np.save(f'./stock_del/{date}_stock_del.npy', np.array(stock_del))
data_array = np.hstack([y_a, y_b, y_c, y_d, y_e, y_f])

广播机制

压缩

np.array 如何进行替换? 【python】numpy array 找出符合条件的数并赋值

null

diagonal

np.where

上三角 or 下三角

def recover(self, ht):
    '''

    Parameters
    ----------
    ht
      : a 1-dimension array with length nk*(nk+1)/2.
    Returns
    -------
    Ht
      : the covariance matrix.
    '''
    size_ = int(np.sqrt(len(ht) * 2))
    Ht_cov = np.zeros((size_ , size_ ))
    return Ht_cov.T[np.triu_indices(Ht_cov.shape[0], k=0)] = ht # k = 1 or k=-1

def fla2mat(input, order='C'):
    """
    input = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9]])
    order: 'C', 'F'
    
    ==>
    
    array([[1, 4, 7],
           [2, 5, 8],
           [3, 6, 9]])
    """
    size_ = int(np.sqrt(max(input.shape[0], input.shape[1])))
    return input.reshape([size_, size_], order=order) 

是否对称

tril_recombine_ht = np.tril(recombine_ht, k=-1)
triu_recombine_ht = np.triu(recombine_ht, k=1).T
print('Ture (Symmetric), False(Asymmetric), result is', ((tril_recombine_ht - triu_recombine_ht) == 0).any())

下三角矩阵变对称阵

tril_recombine_ht = np.tril(recombine_ht, k=-1)  # 下三角矩阵
recombine_ht_ = tril_recombine_ht + tril_recombine_ht.T
row, col = np.diag_indices_from(recombine_ht)
recombine_ht_[row, col] = np.diagonal(recombine_ht)  # 对角线赋值

array 分割

numpy array分割-【老鱼学numpy】

对array 进行切分,切分成多个小矩阵块, split_index为切割对应的行,list形式,元素为整数,例如切三块,split_index中有两个元素

以下函数先对行进行切分,然后对列进行切分,然后对矩阵块元素求和,

def get_element_matrix(recombine_ht_, split_index):
    element_matrix = []
    splits = np.split(recombine_ht_, split_index[:-1], axis=0)
    for split_row in splits:
        split_matrix = np.split(split_row, split_index[:-1], axis=1)
        element_matrix.append([np.sum(element_matrix) for element_matrix in split_matrix])
    return np.vstack(element_matrix)

重新组合,对行和列的位置进行变化, recombine_index为list或者array,必须是整数

recombine_ht = ht[recombine_index, :]
recombine_ht = recombine_ht[:, recombine_index]

array 排序

对degree排序,相同元素,排序结果相同, array的映射 字典dict映射numpy array

sorted_degree = sorted(set(degree_), reverse = True)
dict_degree = dict(zip(sorted_degree, range(1, len(sorted_degree) +1)))
a2 = np.vectorize(dict_degree.get)(degree_)

posted on 2021-10-02 21:18  RankFan  阅读(61)  评论(0编辑  收藏  举报

导航