Why the dtype parameter of pd.Series cannot be used to convert integer strings to ints, but can convert to floats?

Viewed 136

Can someone please explain the following ValueError for me:

>>> import pandas as pd
>>> pd.__version__
'1.3.5'
>>> pd.Series(['1', '2'], dtype='float64')
0    1.0
1    2.0
dtype: float64
>>> pd.Series(['1', '2'], dtype='int64')
C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy\core\numeric.py:2446: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  return bool(asarray(a1 == a2).all())
Traceback (most recent call last):
  File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\interactiveshell.py", line 3444, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-20-171b1b2dceb0>", line 1, in <module>
    pd.Series(['1', '2'], dtype='int64')
  File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py", line 439, in __init__
    data = sanitize_array(data, index, dtype, copy)
  File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\construction.py", line 569, in sanitize_array
    subarr = _try_cast(data, dtype, copy, raise_cast_failure)
  File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\construction.py", line 754, in _try_cast
    subarr = maybe_cast_to_integer_array(arr, dtype)
  File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\dtypes\cast.py", line 2094, in maybe_cast_to_integer_array
    raise ValueError(f"values cannot be losslessly cast to {dtype}")
ValueError: values cannot be losslessly cast to int64
0 Answers
Related