0

I am considerably new to Python.I am willing to stack a few 1-d arrays in python and create a 2-d array using that. The arrays which I want to stack are returned from another function. The minimum reproducible code that I have written for this purpose has been shown below:

def fun1(i): # this function returns the array
  return array # This array is a function of i
h0= np.empty(5,dtype=object)
arrays=[h0]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h=np.vstack(arrays)
print (h)

The desired output is of the form :

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

But I get :

[[None None None None None]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

I understand that I get the above output because an empty array of dtype=object has all elements None . But I am not being able to solve the problem. Any help regarding this would be highly appreciated.

1
  • Why did you use the h0 at all? Commented Jun 1, 2020 at 14:01

3 Answers 3

1

You are getting None because you are creating an empty array with dtype object:

h0 = np.empty(5,dtype=object)

This line creates an array with None elements.

You can remove this line so that it works as you expect:

def fun1(i): # this function returns the array
  return array # This array is a function of i
arrays=[]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h = np.vstack(arrays)
print (h)
Sign up to request clarification or add additional context in comments.

Comments

0
if np.where(~a.any(axis=1))[0]:
    #do nothing
else:
    #print as you like

Comments

0

try this

h = np.vstack([
    fun1(i)
    for i in range(4)
])

print(h)

^^ this is assuming that fun1() is some proprietary function returning arrays of same length

but if you want a 2D array with equal rows entries and incrementing column-wise like

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

you can also try a faster method

x = np.arange(1,5).reshape([-1,1])
h = np.repeat(x, 5, axis= 1)

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.