pythonpandastypesrolling-computation

Why does Pandas rolling method return a series with a different dtype to the original?


Just curious why the Pandas Series rolling window method doesn't preserve the data-type of the original series:

import numpy as np
import pandas as pd

x = pd.Series(np.ones(6), dtype='float32')
x.dtype, x.rolling(window=3).mean().dtype

Output:

(dtype('float32'), dtype('float64'))

Solution

  • x.rolling(window=3) gives you a pandas.core.window.rolling.Rolling object. help(pandas.core.window.rolling.Rolling.mean) includes the note:

     Returns
    -------
    Series or DataFrame
        Return type is the same as the original object with ``np.float64`` dtype.
    

    that's the little why. The big why it would do such a thing, I don't know. Perhaps its a way to keep from loosing precision since you can always choose to convert to float32 again.