11

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']

4

1 に答える 1

17

私の知る限り、純粋に構造化された 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
于 2017-06-22T20:45:10.653 に答える