I'm not sure when to use int()
and when to use .astype('int')
. Can anyone explain?
Is it just int()
is used for single values and .astype('int')
is used for vectors? I'm coming from an R background so I'm used to using as.integer
.astype()
is a method within numpy.ndarray
, as well as the Pandas Series
class, so can be used to convert vectors, matrices and columns within a DataFrame
. However, int()
is a pure-Python function that can only be applied to scalar values.
For example, you can do int(3.14)
, but can't do (2.7).astype('int')
, because Python native types don't have any such method. However, numpy.array([1.1, 2.2, 3.3]).astype('int')
is valid.
(Strictly, it is also possible to define an __int__()
method within one's own classes, which would allow int()
to be applied to non-native types. Thanks to @juanpa.arrivillaga for pointing this out.)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments