How can I make a matrix like mat0 = np.array([[1,2,3],[4,5,6],[7,8,9]])
flatten to an array like arr0 = np.array([1,2,3,4,5,6,7,8,9])
? Or perhaps a set?
Asked
Active
Viewed 346 times
0

user3333975
- 125
- 10
-
What are you doing this for, why do you want a flat array / set? (what's the next step?) – Andy Hayden Mar 07 '14 at 04:45
-
@AndyHayden, I just wanted to be able to do this: `sum((set(mat0.ravel())))` – user3333975 Mar 07 '14 at 05:17
-
It would have been **much** better just to ask that as your question! – Andy Hayden Mar 07 '14 at 05:25
-
I like to ask question--not always though--that are vague enough to simultaneously be answerable for my own agenda, while also providing a foundational starting point for people who land on this page. – user3333975 Mar 07 '14 at 05:27
-
ok, there is better way to get to that solution though! – Andy Hayden Mar 07 '14 at 05:29
-
Let me know if you ask that question :p Basically answer is to stay in numpy (no need to use set) so will be 15x (at least) faster. – Andy Hayden Mar 07 '14 at 05:36
-
@AndyHayden, what? Why not just put it here? – user3333975 Mar 07 '14 at 05:44
-
@AndyHayden, there. How's that? See my title change... ^_^ Wait, never mind. Saw the comments below. It's just `np.sum(np.unique(mat0.ravel()))`, right? – user3333975 Mar 07 '14 at 05:56
-
@AndyHayden, see my answer here: http://stackoverflow.com/a/22241320/3333975 – user3333975 Mar 07 '14 at 06:06
-
yep, pandas' pd.unique is actually faster since it doesn't sort. – Andy Hayden Mar 07 '14 at 07:29
1 Answers
1
Use reshape
:
>>> import numpy as np
>>> mat0 = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> mat0.reshape(-1)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
or ravel
:
>>> mat0.ravel()
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

falsetru
- 357,413
- 63
- 732
- 636
-
-
How do you convert arrays to sets? Like, what if I want the following `[1,1,0]`--->`[1,0]`? – user3333975 Mar 07 '14 at 04:00
-
@user3333975, It's like specifying `9`. If you specify `-1`, the value is infered by the remaining dimensions. – falsetru Mar 07 '14 at 04:00
-
@user3333975, Do you mean `set(mat0.reshape(-1))` or `set(mat0.ravel())` ? – falsetru Mar 07 '14 at 04:01
-
I see, I'm dealing with non-square matrices that change their dimensions often. – user3333975 Mar 07 '14 at 04:02
-
"Do you mean set(mat0.reshape(-1)) or set(mat0.ravel())?" <--- Yes – user3333975 Mar 07 '14 at 04:02
-
@user3333975, If you want to get only unique values, use `numpy.unique` instead of `set`: `np.unique(np.array([1,2,3,3]))`. – falsetru Mar 07 '14 at 05:41
-
@user3333975, And use `numpy.sum` or `sum` method of the array instead of Python builtin function `sum`. – falsetru Mar 07 '14 at 05:41