结构化二维Numpy数组:设置列名和行名

2024-04-29 00:44:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一种很好的方法来获取2d numpy数组,并将列名和行名附加为结构化数组。例如:

import numpy as np

column_names = ['a', 'b', 'c']
row_names    = ['1', '2', '3']

matrix = np.reshape((1, 2, 3, 4, 5, 6, 7, 8, 9), (3, 3))

# TODO: insert magic here

matrix['3']['a']  # 7

我可以使用如下设置列:

matrix.dtype = [(n, matrix.dtype) for n in column_names]

这让我可以做matrix[2]['a'],但现在我想重命名行,这样我就可以做matrix['3']['a']


Tags: 方法importnumpynamesasnpcolumn数组
1条回答
网友
1楼 · 发布于 2024-04-29 00:44:46

据我所知,用纯结构化的NumPy数组“命名”行是不可能的。

但如果有的话,就可以提供一个“索引”(实际上类似于“行名”):

>>> import pandas as pd
>>> import numpy as np
>>> column_names = ['a', 'b', 'c']
>>> row_names    = ['1', '2', '3']

>>> matrix = np.reshape((1, 2, 3, 4, 5, 6, 7, 8, 9), (3, 3))
>>> df = pd.DataFrame(matrix, columns=column_names, index=row_names)
>>> df
   a  b  c
1  1  2  3
2  4  5  6
3  7  8  9

>>> df['a']['3']      # first "column" then "row"
7

>>> df.loc['3', 'a']  # another way to index "row" and "column"
7

相关问题 更多 >