0

How can I do this? I just need a numpy array/dictionary of the form

[ z (an int), [lamda (np float array)], [flux (np float array)] ]

So I can create the 'data25' numpy array below... But when I try to append another record with the same format, I get an error:

data25 = [0.0,sData1['lambda'],sData1['flux']]
print data25
for z in np.arange(0.2,1.0,0.2):
    newLambdaArr = []
    newFluxArr   = []
    for entry in sData1:
        newLambdaArr = np.append(newLambdaArr, [entry[0] * (1.0 + z)])
        newFluxArr   = np.append(newFluxArr,   [entry[1]/(fpi * frw.dl(z) * (1+z))])
    print 'new lambda',newLambdaArr
    print 'new flux', newFluxArr
    temp = [z, newLambdaArr, newFluxArr]
    print 'just built: ', temp
    data25 =  np.append(data25, [temp] )
    print data25

I get the error at the "data25 = np.append..." line:

ValueError: setting an array element with a sequence.

The first "print data25" gives me what I want:

[0.0, array([  9.10000000e+01,   9.40000000e+01,   9.60000000e+01, ...,
     1.20000000e+06,   1.40000000e+06,   1.60000000e+06], dtype=float32), array([  0.00000000e+00,   0.00000000e+00,   0.00000000e+00, ...,
     3.60900003e-08,   1.95199998e-08,   1.14600001e-08], dtype=float32)]

Thx

1
  • Don't use np.append. Use alist.append(newvalue). If you want numpy arrays (as opposed to Python lists), create those explicitly. Commented Dec 1, 2014 at 3:23

1 Answer 1

1

numpy.append works differently, it'll return a single list with the elements inside the list you have as argument so it's not what you want:

>>> np.append([1, 2, 3], [4, 5, 6])
array([1, 2, 3, 4, 5, 6])

Your use case can be done with a simple Python list like this:

>>> z = 5
>>> flux = np.array([1, 2, 3])
>>> lambdas = np.array([4, 5, 6])
>>> data = [z, flux, lambdas]
>>> data
[5, array([1, 2, 3]), array([4, 5, 6])]
# Alternatively you can do data.append(z), data.append(flux) and then data.append(lambdas)

If you want the result to be a numpy array, you'll have to shape it like a multidimensional array:

>>> data = np.array([np.array([z]), flux, lambdas]) # Notice the z integer is passed as an array
>>> data
array([array([5]), array([1, 2, 3]), array([4, 5, 6])], dtype=object)

If you don't shape it like that, you'll get your error:

>>> data = np.array([z, flux, lambdas])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: setting an array element with a sequence.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks... That: data = np.array([np.array([z]), flux, lambdas]) works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.