1

I have got an array of floatsand I would like to cast it into int.

a1 = np.ones(10)
a2 = a1.astype(int, copy=False)
a2.dtype # int
a1.dtype # float

What's going on here? I thought astype(int, copy=False) would cast types in-places. But it doesn't appear to do so?

related question: In-place type conversion of a NumPy array

Community
  • 1
  • 1
colinfang
  • 20,909
  • 19
  • 90
  • 173
  • I thought it might be due to size differences between pure python `int` and `np.float64`, but I tried with `np.int64` but it didn't work either. – wim Feb 24 '14 at 14:20
  • Start reading here: https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/methods.c#L784 – wim Feb 24 '14 at 14:30

1 Answers1

2

From the copy argument documentation:

If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.

It can't actually convert the type in place. It only works if the input array is already of the dtype you want; otherwise, it has to make a copy anyway.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • I think this seems correct, but what can `astype` change, if not the `dtype`? – wim Feb 24 '14 at 14:17
  • @wim: It can only avoid making a new array if the original already looks exactly the way you want it. When making a new array, it can change the dtype, memory order, and particular array subclass. – user2357112 Feb 24 '14 at 14:27
  • This is simply a way of avoiding an unnecessary copy if you have an array object of unknown type and you have to cast it to a specific one. This is probably not that often needed using numpy from Python, where you can get the same operation to work regardless of type, but in the C internals of numpy you see that done all the time. – Jaime Feb 24 '14 at 14:57