BUG: indexing with `at` and Multi-index gives unexpected error

This issue has been created since 2022-09-20.

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

qwe = pd.DataFrame({"b":[3,4,5], "n":[5,4,3], "a":[3,4,5], "c":[5,4,3]})
qwe.columns = pd.MultiIndex.from_tuples([("A", "b"),("A", "n"),("B", "a"),("B", "c")])
qwe["q"] = "asd"
# demo of getter error
print(f" 'loc' getter works fine for qwe.at[0, ('A', 'n')] {qwe.loc[0, ('A', 'n')]}")
print(f" 'at' getter works fine for qwe.at[0, ('A', 'n')] {qwe.at[0, ('A', 'n')]}")
print(f" 'loc' getter works fine for qwe.loc[0, 'q'] {qwe.loc[0, 'q']}")
print(f" 'at' getter doesnt work for qwe.at[0, 'q'] {qwe.at[0, 'q']}")
#demo of setter error
qwe.at[0, ("A", "n")] = 6 # Works fine!
qwe.at[0, "q"] = 6 # Works fine!
qwe.at[0, "q"] = [9,8,7] # Error

Issue Description

Given a dataframe with a multiindex, I can index individual cells using at. I would expect the indexing to work analogously to loc. I have encountered some related errors:

  1. getting an individual cell with at doesn't work when the second level of the multi-index is empty. This is okay to do in loc. i.e. qwe.at[0, 'q'] for getting does not work is the second level of q is empty, but for qwe.loc[0, 'q'] it works.
  2. The same kind of indexing using at for setting does not produce an error when setting a scalar, i.e. qwe.at[0, 'q']=5 is ok
  3. The same kind of indexing using at for setting does produce an error when setting a list, i.e. qwe.at[0, 'q']=[1,2,3] is not ok

Screenshot 2022-09-20 at 16 30 17

Expected Behavior

I would expect at to work analogously to loc for indexing and for the getters and setters to either both work or both not work. I would also expect to be able to insert lists into a cell, even when the dataframe has a multiindex.

Installed Versions

INSTALLED VERSIONS

commit : 87cfe4e
python : 3.10.3.final.0
python-bits : 64
OS : Darwin
OS-release : 21.4.0
Version : Darwin Kernel Version 21.4.0: Fri Mar 18 00:45:05 PDT 2022; root:xnu-8020.101.4~15/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : en_US.UTF-8
LANG : None
LOCALE : en_US.UTF-8

pandas : 1.5.0
numpy : 1.22.4
pytz : 2022.1
dateutil : 2.8.2
setuptools : 58.1.0
pip : 22.1.2
Cython : None
pytest : 7.1.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 8.4.0
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.5.2
numba : 0.55.2
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.8.1
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : 2022.3.0
xlrd : None
xlwt : None
zstandard : None
tzdata : None

Clear Cell Output
Convert to Markdown Cell
Delete Cell
Add Cell Above
Add Cell Below
Visibility
Input
Output
Extended Output
Parameterized Cell
1

Clear Cell Output
Convert to Markdown Cell
Delete Cell
Add Cell Above
Add Cell Below
Visibility
Input
Output
Extended Output
Parameterized Cell
1

phofl wrote this answer on 2022-09-20

Hi, thanks for your report.
Can you please produce the initial df without concat? Hard to see what's going on here

lschwetlick wrote this answer on 2022-09-20

@phofl I did it with pd.MultiIndex.from_tuples. Is that better? I also fixed some details in the description.

lschwetlick wrote this answer on 2022-09-20

Doing it, I also noticed the following, possibly related, difference between implicitly and explicitly setting the multi index. In the implicit version the name of the unused index is an empty string. When setting it explicitely it is NaN.

qwe = pd.DataFrame({"b":[3,4,5], "n":[5,4,3], "a":[3,4,5], "c":[5,4,3]})
qwe.columns = pd.MultiIndex.from_tuples([("A", "b"),("A", "n"),("B", "a"),("B", "c")])
qwe["q"] = "asd"
qwe.columns

->

MultiIndex([('A', 'b'),
            ('A', 'n'),
            ('B', 'a'),
            ('B', 'c'),
            ('q',  '')],
           )

and

qwe = pd.DataFrame({"b":[3,4,5], "n":[5,4,3], "a":[3,4,5], "c":[5,4,3], "q":"asd"})
qwe.columns = pd.MultiIndex.from_tuples([("A", "b"),("A", "n"),("B", "a"),("B", "c"), ("q")])
qwe["q"] = "asd"
qwe.columns

->

MultiIndex([('A', 'b'),
            ('A', 'n'),
            ('B', 'a'),
            ('B', 'c'),
            ('q', nan)],
           )
More Details About Repo
Owner Name pandas-dev
Repo Name pandas
Full Name pandas-dev/pandas
Language Python
Created Date 2010-08-24
Updated Date 2022-09-29
Star Count 35373
Watcher Count 1123
Fork Count 15031
Issue Count 3581

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
Updated build system & new maintainers 0 2022-04-13 2022-09-24
Elegant ota over the internet 0 2022-05-01 2022-08-29
Fails to run on RX 6800 with Radeon Software 21.10.1 4 2021-10-06 2022-03-09
How to create bootable ISO from .IMG? 8 2021-05-04 2022-05-27
Exception in GET /public/logs 0 2022-06-29 2022-09-07
Cant use Github login 3 2021-03-19 2022-09-12
can add controls , button,radio,dropdownbox to datagrid 0 2022-07-10 2022-09-20
how can export data to xls or pdf 0 2022-07-10 2022-08-08
using pyputter on docker giving failure 2 2021-12-15 2022-09-25
Coincident Points Error 0 2022-02-01 2022-09-07
fitz has a dependency on frontend that is not in the package 2 2022-01-15 2022-09-01
"Entry not found in cache" while editing Azure API Management 1 2021-01-28 2022-09-16
Core ML 导出包报错 1 2022-01-14 2022-01-14
[INTEGRATION][Flink] Create SchemaDatasetFacet from Avro schema 3 2022-02-23 2022-09-24
Pllayer-mpris-tail blacklist option not working for chromium. 4 2019-07-29 2022-09-22
[Feature request] AccuWeather's "minutecast" 0 2022-06-24 2022-09-02
Metrics Suggests invalid grouping fields. 0 2022-08-10 2022-09-21
Feature request 2nd AFR table 2 2021-06-18 2022-09-06
Special Okta workarounds welcome in `oauth2-proxy`? 1 2022-02-04 2022-09-20
Accepting an invite where the other party has already left 2 2022-04-05 2022-08-20
I am pretty sure that on 1.16 sorting chest's from expanded storage mod was working but on 1.18 it is not 1 2022-01-07 2022-09-14
🛑 Wedding HTTPS is down 1 2021-12-22 2021-12-21
Set Gateway API `HTTPRoute` status 0 2021-12-23 2022-09-19
Adding a new version defined in a swagger file 4 2022-05-27 2022-07-29
Wrong wording on 'Help' (doc)? 2 2021-10-28 2022-09-23
Docs: Create archive site for 12.x docs 1 2021-10-18 2022-09-11
Touch only works after page is refreshed 0 2022-06-09 2022-08-01
Ability to set audio as mono 2 2021-05-21 2022-09-15
Postgres database update error by osm2pgsql 6 2021-09-17 2022-08-22
TypeError: jhContext.setupServerOptions is not a function 3 2021-04-15 2022-08-24
Can not configure SMTP mail part 8 2020-02-11 2022-09-25
Public poll not usable without sign in "invalid name 1 2021-09-21 2022-08-29
Particle filter in mod_sst.c 0 2021-10-14 2022-09-12
`Data.Parameterized.Vector`: offer function to extract underlying `Data.Vector.Vector` 1 2021-11-03 2022-08-23
RFC: Provide k_realloc() 2 2021-12-14 2021-12-08
Error when LINTERP=.FALSE. 4 2021-05-26 2022-09-12
Removed redundant assignment, and fixed typo 0 2020-07-30 2022-09-27
Cloud function that can point to different environments for testing. 0 2022-08-25 2022-09-24
"APIV2 - PDF Document" does not support custom PDF substitution in Cloud 2 2022-03-11 2022-07-26
Grpc.Core.Internal.AsyncCall<>.UnaryCall hangs (malformed call status?) 8 2022-06-01 2022-09-25
Access vocabulary of Pretrained SentencePiece model using SentencePieceProcessor 2 2021-07-28 2022-09-28
Custom branch naming for 0 2022-05-01 2022-09-28
Workspace-level lints 0 2022-06-25 2022-08-29
[TLS termination] frequent timeout error on connection 4 2021-10-14 2022-09-16
Provide an on demand mechanism to capture profiles 0 2022-09-07 2022-09-24
`TestEtcd` flakiness 0 2022-09-07 2022-09-24
Unable to access Aurora primary endpoint after removing a reader 0 2022-09-07 2022-09-24
上次已经启动的mock组,下次启动的时候期望能自动启动mock 0 2022-03-11 2022-09-12
Add ability for links in the side panel 6 2018-10-21 2022-09-22
cannot search plugin in flipper version 0.147.0 on Ubuntu 22.04 5 2022-05-28 2022-09-27