I have a 2D list something like
我有一个类似的2D列表
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
and I want to convert it to a 2d numpy array. Can we do it without allocating memory like
我想将它转换为2d numpy数组。我们可以在不分配内存的情况下完成
numpy.zeros((3,3))
and then storing values to it?
然后将值存储到它?
4 个解决方案
#1
68
Just pass the list to np.array
:
只需将列表传递给np.array:
a = np.array(a)
You can also take this opportunity to set the dtype
if the default is not what you desire.
如果默认值不是您想要的,您也可以借此机会设置dtype。
a = np.array(a, dtype=...)
#2
2
I am using large data sets exported to a python file in the form
我正在使用导出到表单中的python文件的大型数据集
XVals1 = [.........]
XVals2 = [.........]
Each list is of identical length. I use
每个列表的长度相同。我用
>>> a1 = np.array(SV.XVals1)
>>> a2 = np.array(SV.XVals2)
Then
然后
>>> A = np.matrix([a1,a2])
#3
1
just use following code
只需使用以下代码
c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Then it will give you
然后它会给你
you can check shape and dimension of matrix by using following code
您可以使用以下代码检查矩阵的形状和尺寸
c.shape
c.shape
c.ndim
c.ndim
#4
0
np.array()
is even more powerful than what unutbu said above. You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:
np.array()比unutbu上面说的更强大。您还可以使用它将np数组列表转换为更高维度的数组,以下是一个简单的示例:
aArray=np.array([1,1,1])
bArray=np.array([2,2,2])
aList=[aArray, bArray]
xArray=np.array(aList)
xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.
xArray的形状是(2,3),它是一个标准的np数组。此操作可避免循环编程。
#1
68
Just pass the list to np.array
:
只需将列表传递给np.array:
a = np.array(a)
You can also take this opportunity to set the dtype
if the default is not what you desire.
如果默认值不是您想要的,您也可以借此机会设置dtype。
a = np.array(a, dtype=...)
#2
2
I am using large data sets exported to a python file in the form
我正在使用导出到表单中的python文件的大型数据集
XVals1 = [.........]
XVals2 = [.........]
Each list is of identical length. I use
每个列表的长度相同。我用
>>> a1 = np.array(SV.XVals1)
>>> a2 = np.array(SV.XVals2)
Then
然后
>>> A = np.matrix([a1,a2])
#3
1
just use following code
只需使用以下代码
c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Then it will give you
然后它会给你
you can check shape and dimension of matrix by using following code
您可以使用以下代码检查矩阵的形状和尺寸
c.shape
c.shape
c.ndim
c.ndim
#4
0
np.array()
is even more powerful than what unutbu said above. You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:
np.array()比unutbu上面说的更强大。您还可以使用它将np数组列表转换为更高维度的数组,以下是一个简单的示例:
aArray=np.array([1,1,1])
bArray=np.array([2,2,2])
aList=[aArray, bArray]
xArray=np.array(aList)
xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.
xArray的形状是(2,3),它是一个标准的np数组。此操作可避免循环编程。