2

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.

1
  • Normally a dataframe values is a 2d array (possibly object dtype). But with your groups that isn't possible. Your groups have different sizes. A list of lists is fine. Commented Nov 8, 2020 at 16:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

That's not quite what I am looking for unfortunately but thanks. I was hoping to get [ [ [3 , 4] , [4 , 7] , [5 , 7] ] , [ [2 , 3] , [4 , 5] ] ] instead of [[3, 4], [4, 7], [5, 7], [2, 3], [4, 5]]
The sublists should be grouped by index "a" so this answer is incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.