2017-06-22 3651 views
1

我正試圖找到一個很好的方法來獲取2d numpy數組,並將列名和行名作爲結構化數組附加。例如:結構化二維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']

+0

,因爲我知道這是不可能的,結構化NumPy的陣列。你有熊貓嗎? – MSeifert

+0

我確實有熊貓。你是否建議在Pandas中爲行編制索引? – freebie

+1

不,我會建議使用'index'來訪問行:) – MSeifert

回答

0

據我所知,不可能用純粹結構化的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