Home > OS >  Fillna change type of pandas.Series
Fillna change type of pandas.Series

Time:03-31

In beginning I have DataFrame with int type column. In code i change type to object type, and then apply fillna() method - it changes type back. For example:

import pandas as pd
import numpy as np

data = pd.DataFrame({'a': [2, 5, 7]})
print("Initial type: ", data['a'].dtype)
data['a'] = data['a'].astype('object')
print("Setted type: ", data['a'].dtype)
print("Type after fillna:",  data['a'].fillna('no data').dtype)  

Will return:

Initial type:  int64
Setted type:  object
Type after fillna: int64

You may notice that I have no NaNs in my column, but I need to apply this procedure to a number of columns. So why does it happens and how set fillna so it doesn't change type?

PS. use astype is not appropriate

CodePudding user response:

You can use downcast=False to prevent this:

data['a'].fillna('no data', downcast=False)
  • Related