I have a large dataframe that looks somewhat like this:
a b c
0 2.2 6.0 0.0
1 3.3 7.0 NaN
2 4.4 NaN 3.0
3 5.5 9.0 NaN
Columns b and c contain float values that are either postive, natural numbers or NaN. However, they are stored as float64, which is a problem, since (without going into further detail) this dataframe is the input of a pipeline that requires these to be integers, so and I want to store them as such. The output should look like this:
a b c
0 2.2 6 0
1 3.3 7 NaN
2 4.4 NaN 3
3 5.5 9 NaN
I read in the pandas documentation that nullable integers are only supported in the pandas datatype "Int8" (note: this is different from np.int8), so naturally, I attempted this:
df = df.astype({'b':pd.Int8Dtype(), 'c':pd.Int8Dtype()})
This works when I run it in my Jupyter notebook, but when I integrate it within a larger function, I get this error:
TypeError: cannot safely cast non-equivalent float64 to int8
I understand why I get the error, since x == int(x), will be False for NaN values, so the program thinks this conversion is unsafe, even though all values are either NaN or natural number. So next, I tried:
'df = df.astype({'b':pd.Int8Dtype(), 'c':pd.Int8Dtype()}, errors='ignore')
I figured that this would get rid of the 'unsafe conversion' problem, since I am 100% sure all float64 values are natural numbers. However, when I use this line, all of my numbers are still stored as floats! Infuriating!
Does anyone have a workaround for this?