Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: DataFrame.iloc[idx, column] = array sets incorrect values for 1.5.0 #48835

Closed
2 of 3 tasks
zmeves opened this issue Sep 28, 2022 · 1 comment
Closed
2 of 3 tasks
Labels
Bug Needs Triage Issue that has not been reviewed by a pandas team member

Comments

@zmeves
Copy link

zmeves commented Sep 28, 2022

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

print(f"pandas version: {pd.__version__}")

df = pd.DataFrame({'a': -1, 'b': -2}, 
                  index=pd.MultiIndex.from_product([['AA', 'BB', 'CC', 'DD'],
                                                    list(range(60))]))

df = df.astype(pd.Int32Dtype())

print("\nBefore:")
print(df)

idx = df['a'].notna()  # All True
assert idx.all()

values = np.concatenate([[10] * 60,
                         [20] * 60,
                         [30] * 60,
                         [40] * 60])

print(f"\nSetting all of column 'a' with .loc[idx, 'a'] to:")
print(values)

df.loc[idx, 'a'] = values

print("\nAfter:")
print(df)
print("\nChecking for correct numbers: ")
print(np.all(df['a'] == values))

print(f"\n\nNow setting all of column 'a' with ['a']:")

df['a'] = values
print("\nAfter:")
print(df)
print("\nChecking for correct numbers: ")
print(np.all(df['a'] == values))

Issue Description

You should be able to (and can in all prior pandas versions) set the values of a DataFrame with a boolean index array and a numpy array of values with the proper size, like in the included example:

idx = df['a'].notna()  # This will be a boolean array of all True
print(df.loc[idx, 'a'])  # This properly prints the column 'a' in its correct order

# Try to set values
df.loc[idx, 'a'] = rhs_values  # This should set the entire column to the contents of `rhs_values`, in order

However, doing this results in the data from rhs_values being apparently randomly inserted into column 'a'. All of the values from the array are inserted into column 'a', but they are not set in the same order as they appear in rhs_values, even though the index idx is in the same order as df.index and all True.

The output of the included example is below. After attempting to set with .loc[idx, 'a'], the values in df are not correct. After setting with ['a'], the are correct.

pandas version: 1.5.0

Before:
        a   b
AA 0   -1  -2
   1   -1  -2
   2   -1  -2
   3   -1  -2
   4   -1  -2
...    ..  ..
DD 55  -1  -2
   56  -1  -2
   57  -1  -2
   58  -1  -2
   59  -1  -2

[240 rows x 2 columns]

Setting all of column 'a' with .loc[idx, 'a'] to:
[10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
 10 10 10 10 10 10 10 10 10 10 10 10 20 20 20 20 20 20 20 20 20 20 20 20
 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30
 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30
 30 30 30 30 30 30 30 30 30 30 30 30 40 40 40 40 40 40 40 40 40 40 40 40
 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40
 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40]

After:
        a   b
AA 0   10  -2
   1   30  -2
   2   30  -2
   3   30  -2
   4   30  -2
...    ..  ..
DD 55  20  -2
   56  20  -2
   57  20  -2
   58  40  -2
   59  40  -2

[240 rows x 2 columns]

Checking for correct numbers: 
False


Now setting all of column 'a' with ['a']:

.... FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`
  df.loc[idx, 'a'] = values

After:
        a   b
AA 0   10  -2
   1   10  -2
   2   10  -2
   3   10  -2
   4   10  -2
...    ..  ..
DD 55  40  -2
   56  40  -2
   57  40  -2
   58  40  -2
   59  40  -2

[240 rows x 2 columns]

Checking for correct numbers: 
True

Expected Behavior

The expected behavior is for df.loc[idx, 'a'] = values to set the contents of column 'a' to the given values in the correct order if idx is a boolean array in the same order as df.index.

The included example's output should be:

pandas version: 1.5.0

Before:
        a   b
AA 0   -1  -2
   1   -1  -2
   2   -1  -2
   3   -1  -2
   4   -1  -2
...    ..  ..
DD 55  -1  -2
   56  -1  -2
   57  -1  -2
   58  -1  -2
   59  -1  -2

[240 rows x 2 columns]

Setting all of column 'a' with .loc[idx, 'a'] to:
[10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
 10 10 10 10 10 10 10 10 10 10 10 10 20 20 20 20 20 20 20 20 20 20 20 20
 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30
 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30
 30 30 30 30 30 30 30 30 30 30 30 30 40 40 40 40 40 40 40 40 40 40 40 40
 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40
 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40]

After:  # THIS IS WHAT SHOULD BE CHANGED
        a   b
AA 0   10  -2
   1   10  -2
   2   10  -2
   3   10  -2
   4   10  -2
...    ..  ..
DD 55  40  -2
   56  40  -2
   57  40  -2
   58  40  -2
   59  40  -2

[240 rows x 2 columns]

Now setting all of column 'a' with ['a']:

... FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either `df[df.columns[i]] = newvals` or, if columns are non-unique, `df.isetitem(i, newvals)`
  df.loc[idx, 'a'] = values

After:
        a   b
AA 0   10  -2
   1   10  -2
   2   10  -2
   3   10  -2
   4   10  -2
...    ..  ..
DD 55  40  -2
   56  40  -2
   57  40  -2
   58  40  -2
   59  40  -2

[240 rows x 2 columns]

Checking for correct numbers: 
True

Installed Versions

INSTALLED VERSIONS
------------------
commit           : 87cfe4e38bafe7300a6003a1d18bd80f3f77c763
python           : 3.8.10.final.0
python-bits      : 64
OS               : Windows
OS-release       : 10
Version          : 10.0.19042
machine          : AMD64
processor        : Intel64 Family 6 Model 141 Stepping 1, GenuineIntel
byteorder        : little
LC_ALL           : None
LANG             : None
LOCALE           : English_United States.1252

pandas           : 1.5.0
numpy            : 1.21.4
pytz             : 2021.3
dateutil         : 2.8.2
setuptools       : 56.0.0
pip              : 21.3.1
Cython           : None
pytest           : 5.1.1
hypothesis       : None
sphinx           : 5.1.1
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : 3.0.3
IPython          : None
pandas_datareader: None
bs4              : 4.10.0
bottleneck       : None
brotli           : None
fastparquet      : None
fsspec           : None
gcsfs            : None
matplotlib       : 3.5.0
numba            : None
numexpr          : 2.8.0
odfpy            : None
openpyxl         : 3.0.9
pandas_gbq       : None
pyarrow          : 6.0.1
pyreadstat       : None
pyxlsb           : None
s3fs             : None
scipy            : 1.7.3
snappy           : None
sqlalchemy       : None
tables           : 3.6.1
tabulate         : None
xarray           : None
xlrd             : 2.0.1
xlwt             : 1.3.0
zstandard        : None
tzdata           : None

@zmeves zmeves added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 28, 2022
@phofl
Copy link
Member

phofl commented Sep 28, 2022

Hi, thx for your report. Duplicate of #48701

@phofl phofl closed this as completed Sep 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Needs Triage Issue that has not been reviewed by a pandas team member
Projects
None yet
Development

No branches or pull requests

2 participants