How to return NumPy array from Pandas MultiIndexed Dataframe?

Viewed 127

I have a MultiIndexed pandas Dataframe and I would like to convert this into a numpy array where each element in the first level of the MultiIndex corresponds to a row of the matrix. So given the dataframe below :

df = pd.DataFrame(np.array([[1, 2, 3, 4 ], [2 ,1, 2, 3], [1, 3, 4 , 7], [1, 3, 5 , 7], [ 2 , 3 , 4 , 5]]),
                   columns=['a', 'b', 'c', 'd'])


df = df.set_index(['a','b']).sort_index()

df

enter image description here

I would like to return :

[ [ [3 , 4] , [4 , 7] , [5 , 7] ] , [ [2 , 3] , [4 , 5] ] ]

I have tried using df.unstack().values but am having no success so far. Any tips or pointers in the right directions would be much appreciated.

2 Answers

Try this:

[i.to_numpy().tolist() for _, i in df.groupby('a')]

Output:

[[[3, 4], [4, 7], [5, 7]], [[2, 3], [4, 5]]]

Use list comprehension with groupby level 0 or 'a' in this dataframe.

No need of .unstack(), just use df.values:

print(df.values)

Output:

array([[3, 4],
       [4, 7],
       [5, 7],
       [2, 3],
       [4, 5]])

To get python list:

print(df.values.tolist())

Output:

[[3, 4], [4, 7], [5, 7], [2, 3], [4, 5]]
Related