gpt4 book ai didi

python - numpy 矩阵的映射索引

转载 作者:太空狗 更新时间:2023-10-30 00:08:57 29 4
gpt4 key购买 nike

我应该如何映射 numpy 矩阵的索引?

例如:

mx = np.matrix([[5,6,2],[3,3,7],[0,1,6]]

行/列索引为 0、1、2。

所以:

>>> mx[0,0]
5

假设我需要映射这些索引,将 0, 1, 2 转换成,例如10, 'A', 'B' 方式如下:

mx[10,10] #returns 5
mx[10,'A'] #returns 6 and so on..

我可以设置一个 dict 并使用它来访问元素,但我想知道是否可以像我刚才描述的那样做。

最佳答案

我建议使用 pandas dataframe索引和列分别使用新映射进行行和列索引,以便于索引。它允许我们使用熟悉的 colon 运算符选择单个元素或整行或整列。

考虑一个通用的(非正方形 4x3 形状的矩阵)-

mx = np.matrix([[5,6,2],[3,3,7],[0,1,6],[4,5,2]])

考虑行和列的映射 -

row_idx = [10, 'A', 'B','C']
col_idx = [10, 'A', 'B']

让我们看一下给定示例的工作流程 -

# Get data into dataframe with given mappings
In [57]: import pandas as pd

In [58]: df = pd.DataFrame(mx,index=row_idx, columns=col_idx)

# Here's how dataframe data looks like
In [60]: df
Out[60]:
10 A B
10 5 6 2
A 3 3 7
B 0 1 6
C 4 5 2

# Get one scalar element
In [61]: df.loc['C',10]
Out[61]: 4

# Get one entire col
In [63]: df.loc[:,10].values
Out[63]: array([5, 3, 0, 4])

# Get one entire row
In [65]: df.loc['A'].values
Out[65]: array([3, 3, 7])

最重要的是,我们没有制作任何额外的副本,因为数据帧及其切片仍在索引到原始矩阵/数组内存空间 -

In [98]: np.shares_memory(mx,df.loc[:,10].values)
Out[98]: True

关于python - numpy 矩阵的映射索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010087/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com