Stripers247
Stripers247

Reputation: 2335

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

Upvotes: 8

Views: 26975

Answers (2)

JayPadhya
JayPadhya

Reputation: 65

I went through your code and found out that there is a missing [] for X,Y,Z. The array cannot take two D array as one. Try putting [X,Y,Z] for the array and you shall get the correct answer.

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)

Upvotes: 0

Chris
Chris

Reputation: 46306

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)

Upvotes: 7

Related Questions