python数组增加索引_向numpy数组追加索引

这篇博客展示了如何使用numpy库计算二维数组的相关系数矩阵,并创建索引以访问特定元素。通过`np.corrcoef`计算相关系数,利用`np.equal.outer`和`np.argwhere`创建索引矩阵。提供了多种方式来根据索引访问相关系数,包括转换为两维索引数组或元组形式。
摘要由CSDN通过智能技术生成

以下是代码的修改版本,其中包含一些建议和注释:import numpy as np

# when indices are 0, 1, 2, ... don't use dictionary

# also for integer values use randint

enc_ = np.random.randint(1, 24, (24,))

ret_ = np.random.randint(1, 24, (24,))

data = np.random.rand(24,24)

# np.corrcoef is vectorized, no need to loop:

corr_matrix = np.corrcoef(data)

# the following is the clearest, but maybe not the fastest way of generating

# your index array:

ind_matrix = np.argwhere(np.equal.outer(enc_, ret_))

# this can't be used for indexing directly, you'll have to choose

# one of the following idioms

# EITHER spread to two index arrays

I, J = ind_matrix.T

# or directly I, J = np.where(np.equal.outer(enc_, ret_))

# single index

print(corr_matrix[I[1], J[1]])

# multiple indices

print(corr_matrix[I[[1,2,0]], J[[1,2,0]]])

# whole row

print(corr_matrix[I[1]])

# OR use tuple conversion

ind_matrix = np.array(ind_matrix)

# single index

print(corr_matrix[(*ind_matrix[1],)])

# multiple indices

print(corr_matrix[(*zip(*ind_matrix[[1,2,0]],),)])

# whole row

print(corr_matrix[ind_matrix[1, 0]])

# OR if you do not plan to use multiple indices

as_tuple = list(map(tuple, ind_matrix))

# single index

print(corr_matrix[as_tuple[1]])

# whole row

print(corr_matrix[as_tuple[1][0]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值