In checking the dtypes for columns in a Pandas DataFrame, I realized that the data type for an integer column is np.int64, but what is surprising is that on Unix this equates to int but on Windows it is not. Why do they not behave the same? Is there a way to create the DataFrame in a way that the result is the same when compared using df.dtypes == int?
Here is some sample code to illustrate.
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.__version__
Out[3]: '1.0.1'
In [4]: np.__version__
Out[4]: '1.18.1'
In [5]: data = pd.DataFrame({'col_1': range(5), 'col_2': np.linspace(0, 1, 5)})
In [6]: data.dtypes
Out[6]:
col_1 int64
col_2 float64
dtype: object
In [7]: data.dtypes == float
Out[7]:
col_1 False
col_2 True
dtype: bool
All of that produces the same result on Windows and Unix, but if I compare the dtypes to int on Windows I get
In [8]: data.dtypes == int
Out[8]:
col_1 False
col_2 False
dtype: bool
and on Unix I get
In [8]: data.dtypes == int
Out[8]:
col_1 True
col_2 False
dtype: bool
I tried specifying the datatypes. This works on Unix, I can input the datatypes by adding dtype=(int, float)
In [9]: data = pd.DataFrame({'col_1': range(5), 'col_2': np.linspace(0, 1, 5)}, dtype=(int, float))
In [10]: data.dtypes
Out[10]:
col_1 int64
col_2 float64
dtype: object
but on Windows this code fails with a ValueError
In [10]: data = pd.DataFrame({'col_1': range(5), 'col_2': np.linspace(0, 1, 5)}, dtype=(int, float))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-25-284f0f12d3b6> in <module>
----> 1 data = pd.DataFrame({'col_1': range(5), 'col_2': np.linspace(0, 1, 5)}, dtype=(int, float))
~\Miniconda3\envs\pandas_test\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
423 data = {}
424 if dtype is not None:
--> 425 dtype = self._validate_dtype(dtype)
426
427 if isinstance(data, DataFrame):
~\Miniconda3\envs\pandas_test\lib\site-packages\pandas\core\generic.py in _validate_dtype(self, dtype)
257
258 if dtype is not None:
--> 259 dtype = pandas_dtype(dtype)
260
261 # a compound dtype
~\Miniconda3\envs\pandas_test\lib\site-packages\pandas\core\dtypes\common.py in pandas_dtype(dtype)
1872 # raise a consistent TypeError if failed
1873 try:
-> 1874 npdtype = np.dtype(dtype)
1875 except SyntaxError:
1876 # np.dtype uses `eval` which can raise SyntaxError
ValueError: mismatch in size of old and new data-descriptor