结构化二维 Numpy 数组:设置列名和行名
Structured 2D Numpy Array: setting column and row names
我正在尝试找到一种很好的方法来获取 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']
.
据我所知,不可能 "name" 具有纯结构化 NumPy 数组的行。
但如果您有 pandas,则可以提供 "index"(本质上就像 "row name"):
>>> 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
我正在尝试找到一种很好的方法来获取 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']
.
据我所知,不可能 "name" 具有纯结构化 NumPy 数组的行。
但如果您有 pandas,则可以提供 "index"(本质上就像 "row name"):
>>> 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