question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

BUG: uint16 inserted as int16 when assigning row with dict

See original GitHub issue

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd
import numpy as np

df = pd.DataFrame(columns=["actual", "reference"])
df.loc[0] = {'actual': np.uint16(40_000), 'reference': "nope"}
df

#    actual reference
# 0  -25536      nope

df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1 entries, 0 to 0
Data columns (total 2 columns):
 #   Column     Non-Null Count  Dtype 
---  ------     --------------  ----- 
 0   actual     1 non-null      int16 
 1   reference  1 non-null      object
dtypes: int16(1), object(1)

Issue Description

Inserting a row with a dict, uint16 values are converted to int16 and the value conversion does not preserve the correct value. This also happens when assigning into an existing object-typed column (the conversion sequence seems to be -> int16 -> int in that case).

Expected Behavior

It’s expected the dtype is preserved - uint16 if possible, or an int which is large enough to represent the value.

Installed Versions

python           : 3.8.10.final.0
python-bits      : 64
OS               : Linux
machine          : x86_64

pandas           : 1.4.2
numpy            : 1.22.4
pytz             : 2022.1
dateutil         : 2.8.2
pip              : 20.0.2
setuptools       : 44.0.0
Cython           : None
pytest           : None
hypothesis       : None
sphinx           : None
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : 3.1.2
IPython          : None
pandas_datareader: None
bs4              : None
bottleneck       : None
brotli           : None
fastparquet      : None
fsspec           : None
gcsfs            : None
markupsafe       : 2.1.1
matplotlib       : None
numba            : None
numexpr          : None
odfpy            : None
openpyxl         : None
pandas_gbq       : None
pyarrow          : None
pyreadstat       : None
pyxlsb           : None
s3fs             : None
scipy            : None
snappy           : None
sqlalchemy       : None
tables           : None
tabulate         : None
xarray           : None
xlrd             : None
xlwt             : None
zstandard        : None

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:8 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
simonjayhawkinscommented, Jun 15, 2022

note working in pandas-1.2.5, albeit retaining object dtype from empty DataFrame and then in pandas-1.3.5 overflow but still with object dtype

first bad commit: [549e39bf7a4f925424b39e613895594f48dbb1a5] ENH: Make maybe_convert_object respect dtype itemsize (#40908) cc @rhshadrach

and then in pandas-1.4.2/main overflow but changed (incorrect) dtype.

I suspect as result of https://pandas.pydata.org/pandas-docs/stable/whatsnew/v1.4.0.html#ignoring-dtypes-in-concat-with-empty-or-all-na-columns and that addressing the above regression resolves the dtype issue

1reaction
simonjayhawkinscommented, Jun 15, 2022

Thanks @bluss for the report

note working in pandas-1.2.5, albeit retaining object dtype from empty DataFrame and then in pandas-1.3.5 overflow but still with object dtype and then in pandas-1.4.2/main overflow but changed (incorrect) dtype.

print(pd.__version__)
df = pd.DataFrame(columns=["actual", "reference"])
df.loc[0] = {"actual": np.uint16(40_000), "reference": "nope"}
print(df)
print(df.dtypes)

# 1.2.5
#   actual reference
# 0  40000      nope
# actual       object
# reference    object
# dtype: object

# 1.3.5
#    actual reference
# 0  -25536      nope
# actual       object
# reference    object
# dtype: object

# 1.4.2
#    actual reference
# 0  -25536      nope
# actual        int16
# reference    object
# dtype: object
Read more comments on GitHub >

github_iconTop Results From Across the Web

Pandas DataFrame Assignment Bug using Dictionaries of ...
Problem. Pandas seems to support using df.loc to assign a dictionary to a row entry, ...
Read more >
IO tools (text, CSV, HDF5, …) — pandas 1.5.2 documentation
Column(s) to use as the row labels of the DataFrame , either given as string name or column ... Dict of functions for...
Read more >
Overview of Pandas Data Types - Practical Business Python
int64, int, int_, int8, int16, int32, int64, uint8, uint16, uint32, uint64 ... After looking at the automatically assigned data types, ...
Read more >
astropy.io.fits History — Astropy v0.2.dev2728
FITS HDUs contain an entire FITS file embedded in their data section. ... Fixed a bug where writing a table with zero rows...
Read more >
Data Types and In-Memory Data Model - Apache Arrow
In [27]: pa.array([1, 2], type=pa.uint16()) Out[27]: <pyarrow.lib. ... Arrow data is immutable, so values can be selected but not assigned.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found