0

Code

import numpy as np

arr3 = np.array([], dtype=float)
val=1
for i in range(7):
    if i == 0 or i == 3:
        np.append(arr3,np.nan)
    else:       
        np.append(arr3,val)
        val+=1
arr3

Output

array([], dtype=float64)

When I run this code it does not provide any output. I don't know the reason.

3
  • Why didn't you use list append? np.append is a poor imitation of something works better. Commented Apr 27, 2019 at 15:55
  • i created the array using numpy package so i thought that i should use one of those functions provided in numpy for managing the array. Commented Apr 28, 2019 at 15:51
  • Iterative stuff is usually faster with lists. Commented Apr 28, 2019 at 16:29

2 Answers 2

1

Note that as numpy.append docs says append does not occur in-place, that is numpy.append returns new array. Consider following example:

import numpy as np
arr = np.array([0],dtype='uint8')
arr2 = np.append(arr,1)
print(arr) #[0]
print(arr2) #[0 1]

Your code should work after altering following lines:

np.append(arr3,np.nan)

to

arr3=np.append(arr3,np.nan)

and

np.append(arr3,val)

to

arr3=np.append(arr3,val)
Sign up to request clarification or add additional context in comments.

Comments

0

List append is faster than np.append (or any of the other variations on np.concatenate). List append works in-place, adding a 'pointer' to the existing list. np.concatenate (even with the np.append cover) creates a new array each call, requiring a full copy. If you must build an array iteratively, use lists:

In [85]: alist = []                                                                  
In [86]: val=1                                                                       
In [87]: for i in range(7): 
    ...:     if i==0 or i==3: 
    ...:         alist.append(np.nan) 
    ...:     else: 
    ...:         alist.append(val) 
    ...:         val +=1 
    ...:                                                                             
In [88]: alist                                                                       
Out[88]: [nan, 1, 2, nan, 3, 4, 5]
In [89]: arr = np.array(alist)                                                       
In [90]: arr                                                                         
Out[90]: array([nan,  1.,  2., nan,  3.,  4.,  5.])

Comments

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.