'Fillna change type of pandas.Series
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
Solution 1:[1]
You can use downcast=False to prevent this:
data['a'].fillna('no data', downcast=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TimO |
