use*_*374 6 python dictionary numpy matrix
我应该如何映射numpy矩阵的索引?
例如:
mx = np.matrix([[5,6,2],[3,3,7],[0,1,6]]
Run Code Online (Sandbox Code Playgroud)
行/列索引是0,1,2.
所以:
>>> mx[0,0]
5
Run Code Online (Sandbox Code Playgroud)
假设我需要映射这些索引,转换0, 1, 2成例如10, 'A', 'B'以下方式:
mx[10,10] #returns 5
mx[10,'A'] #returns 6 and so on..
Run Code Online (Sandbox Code Playgroud)
我可以设置一个dict并使用它来访问元素,但我想知道是否可以像我刚才描述的那样做.
我建议将pandas数据帧与索引和列一起使用,分别使用行和列索引的新映射,以便于索引。它允许我们使用熟悉的运算符选择单个元素或整个行或列colon。
考虑一个通用的(非方形 4x3 形状的矩阵) -
mx = np.matrix([[5,6,2],[3,3,7],[0,1,6],[4,5,2]])
Run Code Online (Sandbox Code Playgroud)
考虑行和列的映射 -
row_idx = [10, 'A', 'B','C']
col_idx = [10, 'A', 'B']
Run Code Online (Sandbox Code Playgroud)
让我们看一下给定示例的工作流程 -
# 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])
Run Code Online (Sandbox Code Playgroud)
最重要的是,我们没有制作任何额外的副本,因为数据帧及其切片仍然索引到原始矩阵/数组内存空间 -
In [98]: np.shares_memory(mx,df.loc[:,10].values)
Out[98]: True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |