2016-10-26 15 views
3

からパンダパネルを構築:は、私は構造体の2D numpyの配列を持つ2次元構造numpyの配列

arr = np.zeros((3,5), [('x',int), ('y',float)]) 

つまり:

array([[(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0)], 
     [(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0)], 
     [(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0)]], 
     dtype=[('x', '<i8'), ('y', '<f8')]) 

私はそれからパンダパネルを作成したいです。

<class 'pandas.core.panel.Panel'> 
Dimensions: 3 (items) x 5 (major_axis) x 2 (minor_axis) 
Items axis: 0 to 2 
Major_axis axis: 0 to 4 
Minor_axis axis: x to y 

この "作品" が、非常に非効率的と目障りです:

pd.Panel(dict(enumerate(pd.DataFrame(a) for a in arr))) 

それが生成する:

pd.Panel(arr) 

ValueError: The number of dimensions required is 3, but the number of dimensions of the ndarray given was 2

は、その後、私はこの恐ろしい山を発見した:私は明白なことを試してみました。

このようなパネルはどのように構成されるのですか?

編集:https://github.com/pandas-dev/pandas/issues/14511

+0

あなたは後にしている最終的な形状とは何ですか? pd.Panel(arr.reshape(arr.shape [0]、arr.shape [1]))) 'または' pd.Panel(arr.reshape((arr.shape [0]、arr .shape [1]、1))) '? – EdChum

+0

@EdChum:私が質問で書いた恐ろしい杭によって与えられた最終的な形はOKです。あなたが書いたコードはパネルを生成しますが、 'arr'のデータではなくNaNでいっぱいです!私は、恐ろしい山の結果を示すために質問を更新します。 –

答えて

3

あなたは項目、パネルオブジェクトのメジャーとマイナーの軸に対応する3次元アレイを提供する必要があります:私はここでの問題を提出しました。

# minor axis corresponds to the dtype names of the array initialized with zeros 
dtyp = np.array(arr.dtype.names) 
# dimensions to be included 
dim = arr.shape[0], arr.shape[1], dtyp.shape[0] 
# Flatten the array and reshape it according to the aforementioned dimensions 
panel = pd.Panel(pd.DataFrame(arr.ravel()).values.reshape(dim), minor_axis=dtyp) 

ができます:

<class 'pandas.core.panel.Panel'> 
Dimensions: 3 (items) x 5 (major_axis) x 2 (minor_axis) 
Items axis: 0 to 2 
Major_axis axis: 0 to 4 
Minor_axis axis: x to y 

をそのように、単にto_frameメソッドを使用し、DFに変換するには:

panel.to_frame() 

Image

タイミング:

Image

+0

あなたの方法は確かに高速ですが、それは私のオリジナルよりも簡潔です。 Panelには3D配列が必要ですが、まさに2D構造の配列とまったく同じです。結局のところ、DataFrameは1D構造の配列から構築することができます。これはPanelコンストラクタの単なる欠点だと思います。 –

+0

ええ、私はそれに同意します。現在のパネルオブジェクトは、その機能がデータフレーム/シリーズのものと比較して低いです。将来、3つの軸numpy配列の構築に対処する方法がなければならない。 –

+0

私はちょうどあなたのソリューションで他の問題を認識しました:それは浮動小数点型にすべてのアイテムの種類を変更!実際にはbool、string、datetimesなども使用しているので、オリジナルのdtypeを保持する必要があります。 –

関連する問題