user0
user0

Reputation: 195

Multidimensional numpy.ndarray from multi-indexed pandas.DataFrame

I want to produce a 3-dimensional numpy.ndarray from a multi-indexed pandas.DataFrame. More precisely, say I have:

df = pd.DataFrame([[1, '1' , 1, 10], [1, '2', 2, 20], [2, '1', 5, 30]], columns=['x', 'y', 'z', 't'])
df = df.set_index(['x','y'])
df

which gives me

        z  t
  x  y
  1  1  1 10
     2  2 20
  2  1  5 30

and I want to write a function which returns, with the above argument, the numpy.ndarray

  [[[1, 10],
    [2, 20]],
   [[5, 30],
    [NaN, NaN]]]

Pandas multi-index looks like a substitute for multidimensional arrays, but it does not provide (or at least does not document) ways to go back and forth...

Thanks.

Upvotes: 0

Views: 85

Answers (1)

Tarifazo
Tarifazo

Reputation: 4343

Use:

df.to_xarray().to_array().values.transpose(1,2,0)

>>[[[ 1. 10.]
  [ 2. 20.]]

 [[ 5. 30.]
  [nan nan]]]

Upvotes: 1

Related Questions