pandas.Series.fillna change type of the column

Question:

After changing type of columns in pandas.DataFrame from int64 to object, fillna, applied to this column, returns columns with int64 type again. For example:

import pandas as pd

data = pd.DataFrame({"a" : [2, 3]})

# changing type to 'object'
data['a'] = data['a'].astype('object')
print("type after astype -", data['a'].dtype)

# applying fillna
data["a"] = data["a"].fillna("no data")
print("type after fillna -", data['a'].dtype)

Will return:

type after astype - object
type after fillna - int64

How fix it, without using astype again.

Asked By: Dranikf

||

Answers:

You can use downcast=False to prevent this:

data['a'].fillna('no data', downcast=False)
Answered By: TimO
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.