fre*_*bie 7 python arrays numpy structured-array
我正在尝试找到一种很好的方法来获取一个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
Run Code Online (Sandbox Code Playgroud)
我已经能够使用像这样设置列:
matrix.dtype = [(n, matrix.dtype) for n in column_names]
Run Code Online (Sandbox Code Playgroud)
这让我做,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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9225 次 |
| 最近记录: |