Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 3 lists into 1 3D Numpy array

I have three lists that I want to convert into one list. When I try the following a get this error

 A = numpy.array(X,Y,Z,dtype=float)
 ValueError: only 2 non-keyword arguments accepted

I did not see anything here that says you can only give it two arguments

http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html

Here is the code

import numpy
from numpy import *

X = []
Y = []
Z = []

f = open(r'C:\My.txt')
f.readline()
for line in f:
 if line != '':
     line = line.strip()
     columns = line.split()
     x = columns[2]
     y = columns[3]
     z = columns[4]
     X.append(x)
     Y.append(y)                #appends data in list
     Z.append(z)



A = numpy.array(X,Y,Z,dtype=float)
A.shape(3,3)
print(A)

Thanks in advanceh

like image 967
Stripers247 Avatar asked Mar 27 '12 09:03

Stripers247


People also ask

How do I combine multiple NumPy arrays into one?

You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array.

How do you make a NumPy 3D array?

Use numpy. array() to create a 3D NumPy array with specific values. Call numpy. array(object) with object as a list containing x nested lists, y nested lists inside each of the x nested lists, and z values inside each of the y nested lists to create a x -by- y -by- z 3D NumPy array.

How do you make a 3x3 array in python?

You can use numpy. First, convert your list into numpy array. Then, take an element and reshape it to 3x3 matrix.

Can we convert list to NumPy array?

You can convert a list to a NumPy array by passing a list to numpy. array() . The data type dtype of generated numpy. ndarray is automatically determined from the original list but can also be specified with the dtype parameter.


1 Answers

Try passing your three lists as a tuple:

A = numpy.array((X, Y, Z), dtype=float)

In the numpy.array documentation the signature for numpy.array is

numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0, maskna=None, ownmaskna=False)

i.e. the single argument object is what gets turned into an ndarray, every other argument must be a keyword argument (hence the error message which you were getting) which can be used to customise the creation of the array.

Edit In respone to Surfcast23's comment, in the IDE I tried the following:

>>> import numpy

>>> x = [0, 0, 0, 0]
>>> y = [3, 4, 4, 3]
>>> z = [3, 4, 3, 4]

>>> A = numpy.array((x, y, z), dtype=float)
>>> A
array([[ 0., 0., 0., 0.],
       [ 3., 4., 4., 3.],
       [ 3., 4., 3., 4.]])
>>> A.shape
(3L, 4L)
like image 180
Chris Avatar answered Oct 20 '22 03:10

Chris