[英]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']
。
据我所知,用纯结构化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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.