Numpy matrix to array
If you'd like something a bit more readable, you can do this:
A = np.squeeze(np.asarray(M))
Equivalently, you could also do: A = np.asarray(M).reshape(-1)
, but that's a bit less easy to read.
Convert numpy matrix into 1D numpy array
The type numpy.matrix
is already a subclass of numpy.ndarray
, so no conversion needs to take place:
>>> np.ravel(a.sum(axis=0))
array([1, 2, 2, 0])
What are the differences between numpy arrays and matrices? Which one should I use?
As per the official documents, it's not anymore advisable to use matrix class since it will be removed in the future.
https://numpy.org/doc/stable/reference/generated/numpy.matrix.html
As other answers already state that you can achieve all the operations with NumPy arrays.
convert a 2D numpy matrix to 2D numpy array
Note that a numpy.matrix
is already an ndarray
subclass, and nothing more than a specialized 2D array. Hence you're most likely quite alright without converting your matrix to an explicit numpy.array
unless you have a particular reason to do so, perhaps the additional generality of a Numpy array.
Should this be the case, you can convert your matrix to an array with numpy.asarray()
. It's important you use this method and not numpy.asanyarray()
in your case as with numpy.asanyarray()
allows subclasses of ndarray
to pass through, as your matrix would.
setting values in numpy matrix with array of indices
you can use:
B[np.arange(B.shape[0]),np.argmax(A,1)] = 0
How to convert list of numpy arrays into single numpy array?
In general you can concatenate a whole sequence of arrays along any axis:
numpy.concatenate( LIST, axis=0 )
but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.
As Jorge's answer points out, there is also the function stack
, introduced in numpy 1.10:
numpy.stack( LIST, axis=0 )
This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n
-element 1D array becomes a 1-by-n
2D array) before concatenating. It will only work if all the input arrays have the same shape.
vstack
(or equivalently row_stack
) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:
numpy.vstack( LIST )
This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ]
(note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST
.
There is also an analogous function column_stack
and shortcut c_[...]
, for horizontal (column-wise) stacking, as well as an almost-analogous function hstack
—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).
Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:
numpy.array( LIST )
...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.
What is the best way to convert a SymPy matrix to a numpy array/matrix
This answer is based on the advices from Krastanov and asmeurer. This little snippet uses sympy.lambdify:
from sympy import lambdify
from sympy.abc import x, y
g = sympy.Matrix([[ x, 2*x, 3*x, 4*x, 5*x, 6*x, 7*x, 8*x, 9*x, 10*x],
[y**2, y**3, y**4, y**5, y**6, y**7, y**8, y**9, y**10, y**11]])
s = (x, y)
g_func = lambdify(s, g, modules='numpy')
where g
is your expression containing all symbols grouped in s
.
If modules='numpy'
is used the output of function g_func
will be a np.ndarray
object:
g_func(2, 3)
#array([[ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
# [ 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147]])
g_func(2, y)
#array([[2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
# [y**2, y**3, y**4, y**5, y**6, y**7, y**8, y**9, y**10, y**11]], dtype=object)
If modules='sympy'
the output is a sympy.Matrix
object.
g_func = lambdify(vars, g, modules='sympy')
g_func(2, 3)
#Matrix([[2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
# [9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147]])
g_func(2, y)
#Matrix([[ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
# [y**2, y**3, y**4, y**5, y**6, y**7, y**8, y**9, y**10, y**11]])
vectorize array: construct matrix with 1 in specified places and 0 elsewhere
You can use an np.arange(..)
for the second axis:
def vectorize(a, L, N):
m = np.zeros((N, L), int)
m[a, np.arange(len(a))] = 1
return m
So for the given sample input, we get:
>>> a = np.array([1,2,0,4])
>>> vectorize(a, 4, 5)
array([[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1]])
Create a matrix out of an array
Think you probably just want .reshape()
:
In [2]: a = np.arange(25)
In [3]: a
Out[3]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24])
In [4]: a.reshape(5,5)
Out[4]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
You can also convert it into an np.matrix
after if you need things from that:
In [5]: np.matrix(a.reshape(5,5))
Out[5]:
matrix([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
EDIT: If you've got a list to start, it's still not too bad:
In [16]: l = range(25)
In [17]: np.matrix(np.reshape(l, (5,5)))
Out[17]:
matrix([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
Related Topics
Django Gunicorn Not Load Static Files
How to Change the Styles of Pandas Dataframe Headers
Google Fonts (Ttf) Being Ignored in Qtwebengine When Using @Font Face
How to Use Tailwindcss with Django
Does Python Have a Module to Convert CSS Styles to Inline Styles for Emails
Replicating Jupyter Notebook Pandas Dataframe HTML Printout
How to Customise Qgroupbox Title in Pyqt5
Add Custom CSS Styling to Model Form Django
How to Compile Opencv for iOS7 (Arm64)
Calling R Script from Python Using Rpy2
Quick Way to Upsample Numpy Array by Nearest Neighbor Tiling
Convert Decimal Mark When Reading Numbers as Input
A Mutable Type Inside an Immutable Container
Python Giving Filenotfounderror for File Name Returned by Os.Listdir
Why Doesn't This Division Work in Python
Fastapi Runs API-Calls in Serial Instead of Parallel Fashion