Home > OS >  create a numpy array of zeros with same dtype as another array but different shape
create a numpy array of zeros with same dtype as another array but different shape

Time:02-24

How can I create a NumPy array f zeros with the same dtype as another array? I know about zeros_like() but it gives the same shape as the passed array. I am looking for a different shape but the same dtype as the source array.

CodePudding user response:

NumPy array's have a attribute called dtype. Simply use this attribute when creating a new array with the same data type.

a = np.array([0,1,2])
print(a.dtype) # dtype('int64')
b = np.array([3.1,4.1,5.1], dtype=a.dtype)
print(b) # array([3, 4, 5])
  • Related