Skip to content

[Python] Converting a python sequence of floats to an arrow integer array silently truncates even when safe=True #35584

Closed as not planned

Description

@wirable23

Describe the bug, including details regarding any error messages, version, and platform.

>>> a = pa.array([1.2], type=pa.int64())
>>> a
<pyarrow.lib.Int64Array object at 0x000002BD16EB9F60>
[
  1
]

# The following example is kept in for historical purposes but this is a separate problem and should be
# discussed in https://github.com/apache/arrow/issues/35563
>>> pa.array([18014398509481983],type=pa.float64())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pyarrow\array.pxi", line 327, in pyarrow.lib.array
  File "pyarrow\array.pxi", line 39, in pyarrow.lib._sequence_to_array
  File "pyarrow\error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
  File "pyarrow\error.pxi", line 100, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: Integer value 18014398509481983 is outside of the range exactly representable by a IEEE 754 double precision value
>>>

Data was rounded for double to int64 but not int64 to double.

Component(s)

Python

Activity

  1. zfoobar commented on May 16, 2023

    @zfoobar

    See below - doesn't this indicate a more severe issue?

    18014398509481984 should be representable as a float64 without any conversion errors/rounding.

    >>> float(18014398509481983)
    1.8014398509481984e+16
    >>> int(1.8014398509481984e+16)
    18014398509481984
    >>> a = pa.array([18014398509481984], type=pa.float64())
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "pyarrow/array.pxi", line 327, in pyarrow.lib.array
        result = _sequence_to_array(obj, mask, size, type, pool, c_from_pandas)
      File "pyarrow/array.pxi", line 39, in pyarrow.lib._sequence_to_array
        chunked = GetResultValue(
      File "pyarrow/error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
        return check_status(status)
      File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status
        raise ArrowInvalid(message)
    pyarrow.lib.ArrowInvalid: Integer value 18014398509481984 is outside of the range exactly representable by a IEEE 754 double precision value

    Screenshot 2023-05-16 at 12 50 56 PM

  2. zfoobar commented on May 16, 2023

    @zfoobar

    Any idea why this was implemented this way and not just converted forward and back using C++ data types? Why reimplement?

    Status IntegerScalarToDoubleSafe(PyObject* obj, double* out) {
      int64_t value = 0;
      RETURN_NOT_OK(UnboxIntegerAsInt64(obj, &value));
    
      constexpr int64_t kDoubleMax = 1LL << 53;
      constexpr int64_t kDoubleMin = -(1LL << 53);
    
      if (value < kDoubleMin || value > kDoubleMax) {
        return Status::Invalid("Integer value ", value, " is outside of the range exactly",
                               " representable by a IEEE 754 double precision value");
      }
      *out = static_cast<double>(value);
      return Status::OK();
    }
  3. westonpace commented on May 18, 2023

    @westonpace
    Member

    The int -> double behavior is a duplicate of #35563 I believe.
    The double -> int behavior is by design.

  4. wirable23 commented on May 18, 2023

    @wirable23
    Author

    Thanks @westonpace for the clarification. The API for pa.array is documented to be safe by default. In the cast compute API, truncation is considered unsafe. So what is the reason that in this API, truncation is safe, but in the cast API, truncation is considered unsafe?

    a = pa.array([1.2])
    a
    <pyarrow.lib.DoubleArray object at 0x000002BD16F34EE0>
    [
    1.2
    ]
    a.cast(pa.int64())
    Traceback (most recent call last):
    File "", line 1, in
    File "pyarrow\array.pxi", line 935, in pyarrow.lib.Array.cast
    File "C:\ca2_ps_311\Lib\site-packages\pyarrow\compute.py", line 400, in cast
    return call_function("cast", [arr], options, memory_pool)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "pyarrow_compute.pyx", line 572, in pyarrow._compute.call_function
    File "pyarrow_compute.pyx", line 367, in pyarrow._compute.Function.call
    File "pyarrow\error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
    File "pyarrow\error.pxi", line 100, in pyarrow.lib.check_status
    pyarrow.lib.ArrowInvalid: Float value 1.2 was truncated converting to int64

    In a safe cast, the truncation is raised, but in the safe array creation, all other conditions are checked except truncation. But if this is by design, then this issue can just be closed then?

  5. westonpace commented on May 18, 2023

    @westonpace
    Member

    Interesting, I wasn't aware there was a safe flag for pa.array. It appears we are not using it when converting from a python sequence.

    import numpy as np
    import pandas as pd
    import pyarrow as pa
    
    # From numpy respects safe
    pa.array(np.array([1.2]), pa.int64()) # Fails
    pa.array(np.array([1.2]), pa.int64(), safe=False) # Succeeds
    pa.array(pd.Series([1.2]), pa.int64()) # Fails
    pa.array(pd.Series([1.2]), pa.int64(), safe=False) # Succeeds
    pa.array(pa.array([1.2]), pa.int64()) # Fails
    pa.array(pa.array([1.2]), pa.int64(), safe=False) # Succeeds
    pa.array([1.2], pa.int64()) # Succeeds, but probably shouldn't
    pa.array([1.2], pa.int64(), safe=False) # Succeeds
    

    Thus, I've changed my mind, I agree that pa.array([1.2], type=pa.int64()) should fail. However, that's both a backwards incompatible change and probably not a trivial feature (there is a wholly separate code path for converting python sequences to arrays and it doesn't seem to have a notion of safe casting right now).

  6. changed the title [-]Creating integer array with floating value succeeds[/-] [+][Python] Creating integer array with floating value succeeds[/+] on May 18, 2023
  7. danepitkin commented on May 18, 2023

    @danepitkin
    Member

    Interesting, I wasn't aware there was a safe flag for pa.array. It appears we are not using it when converting from a python sequence.

    Relevant issue here: #31857. It does indeed take a different code path when converting from python to arrow.

  8. jorisvandenbossche commented on May 25, 2023

    @jorisvandenbossche
    Member

    #35584 (comment) Any idea why this was implemented this way and not just converted forward and back using C++ data types? Why reimplement?

    Note that, although this is indeed "reimplemented" in the pyarrow conversion code, this implementation is consistent with the casting code in C++.
    And whether this "check if value is withing fixed range" is the desired behaviour, or we want to relax this to larger ints that are representable as float, that's a discussion for #35563

  9. jorisvandenbossche commented on May 25, 2023

    @jorisvandenbossche
    Member

    Putting some responses to the comments at #35563 (comment) and below here:

    @zfoobar I also answered this just above: I think the "design decision" here was just to be consistent with our C++ casting behaviour (i.e. the behaviour discussed in #35563).

    Nowadays, I would say it's primarily a legacy implementation that eventually should be rewritten to take advantage of the compute kernels in C++ if possible.

    The python_to_arrow.cc code is certainly not legacy code, it's the actual interface between python land and arrow (C++) land, and that's something we will always need to implement in pyarrow, to be able to convert builtin Python objects to Arrow data.
    The C++ compute kernels don't deal with python objects. We of course can try to reuse as much as possible of those (cast) kernels in the python->arrow implementation (eg for IntegerScalarToDoubleSafe we could also extract the integer, convert it to a arrow integer scalar, and then call the int->float cast kernel, so we reuse the safe logic of the cast kernel). But that might be a quite big refactor (and for which we would also need to evaluate the performance impact).

  10. westonpace commented on Jun 1, 2023

    @westonpace
    Member

    Note that, although this is indeed "reimplemented" in the pyarrow conversion code, this implementation is consistent with the casting code in C++.
    And whether this "check if value is withing fixed range" is the desired behaviour, or we want to relax this to larger ints that are representable as float, that's a discussion for #35563

    @jorisvandenbossche

    I'm not sure it is consistent. Note that the original discussion here is not about "large values that are outside the range of safely representable doubles" but about "is truncation safe?"

    #35584 (comment)

  11. jorisvandenbossche commented on Jun 1, 2023

    @jorisvandenbossche
    Member

    @westonpace we are mixing two things here, I think. The top post has two examples: float truncation and large integer outside of float range. My answer was to comments from @zfoobar about the second example (e.g. #35584 (comment)), but the title is about the first example (making this a confusing mixed discussion).

    I fully agree that the float truncation does not match the C++ casting semantics of safe by default (and that's the general underlying issue: the python_to_arrow.cc code path doesn't implement the different notions of safe=True vs safe=False, while the numpy_to_arrow.cc code path uses the C++ casting machinery and its implementation of safe)

  12. westonpace commented on Jun 9, 2023

    @westonpace
    Member

    @jorisvandenbossche yes, I agree there are two issues here. I was hoping we could use this issue for float truncation and use #35563 for out-of-range. I will update the title of this issue to reflect this.

  13. changed the title [-][Python] Creating integer array with floating value succeeds[/-] [+][Python] Converting a python sequence of floats to an arrow integer array silently truncates even when safe=True[/+] on Jun 9, 2023
  14. AlenkaF commented on Jun 21, 2023

    @AlenkaF
    Member

    We created an "umbrella" issue that includes all the issues opened and connected to the Python to array conversion following the code path in python_to_arrow.cc. See: #36202.

    To sum up:

    1. The first part of the issue reported which is the float truncation: as we are starting from a list the python-sequence code path is taken (python_to_arrow.cc) and in case of of float -> int the conversion is unsafe by default (inconsistent with numpy code path). The separate issue to track this is: [C++][Python] Python to Arrow array conversion sometimes ignores "safe=False" or is using unsafe instead of safe cast #36202.
    2. The second part (large integer outside of float range) also has a separate issue created (as already mentioned): [C++] Allow safe cast from int64 to float64 in compute kernel for numerics that can be accurately represented above 2^53 #35563
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions