I have a Series with integer entries, but also some null entries. It is represented as a Series with dtype=float64
. I would like to convert it to a Series with dtype=object
, where the integer entries are stored as Python int
s and the null entries are stored as np.nan
s.
I have two attempts below. The first doesn't work, as the int
is (unexpectedly?) still converted to a float
. The second works as I would hope.
s = pd.Series([1, np.nan])
s = s.astype(object)
i = s.notnull()
s[i] = s[i].astype(int)
type(s[0])
Above snippet returns float
. :(
s = pd.Series([1, np.nan])
s = s.astype(object)
i = s.notnull()
s[i] = list(s[i].astype(int))
type(s[0])
Above snippet returns int
. :)
Why does the first example not work, even though the Series has dtype=object
? Converting to a list
seems like a really weird hack to get this to work, but I couldn't find any other way to do it.
Is there a simpler way to do this in Pandas?