Skip to content

Surprising type conversion when iterating #20791

Open
@mitar

Description

@mitar

Code Sample, a copy-pastable example if possible

>>> df = pandas.DataFrame({'ints': range(5)})
>>> type(df.iloc[:, 0][0])
<class 'numpy.int64'>
>>> type(list(df.iloc[:, 0])[0])
<class 'int'>

Problem description

When iterating over a series, values are being converted to closest Python type and not left as an original type. This is problematic because it is a surprising change and leads to data manipulation one does not expect. One would hope that you can easily get what you stored into a dataframe out when iterating and not a variation of it.

The issue is that iterating uses internally numpy's tolist which has this behavior. This is problematic for two reasons: it constructs the whole list first in memory (#20783) and converts to "closest Python type".

Expected Output

>>> df = pandas.DataFrame({'ints': range(5)})
>>> type(df.iloc[:, 0][0])
<class 'numpy.int64'>
>>> type(list(df.iloc[:, 0])[0])
<class 'numpy.int64'>

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Linux
OS-release: 4.13.0-38-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.22.0
pytest: 3.3.0
pip: 9.0.1
setuptools: 38.2.3
Cython: 0.28.2
numpy: 1.14.2
scipy: 1.0.0
pyarrow: 0.9.0
xarray: None
IPython: 6.2.1
sphinx: None
patsy: 0.4.1
dateutil: 2.6.1
pytz: 2017.3
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.1.0
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: 0.999999999
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.9.4
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

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