Skip to content

pandas/tuple-slice-on-levels

Rule tuple-slice-on-levels
Pack pandas
Severity info
Fix safe, with xpd check --fix
Library versions every version

A tuple with slice(None) in .loc is hard to read. Write the same selection with pd.IndexSlice and a colon.

rows = df.loc[("a", slice(None), 1), :]
rows = df.loc[pd.IndexSlice["a", :, 1], :]

The rule reports a tuple with slice(None) inside .loc[...], on the rows or on the columns. pd.IndexSlice["a", :, 1] was equal to ("a", slice(None), 1), and .loc gave equal frames with the two. A slice that has bounds, as in slice("a", "c"), becomes "a":"c", and pd.IndexSlice builds the same tuple.

xpd check --fix applies the fix of this rule.

The safe fix writes pd.IndexSlice["a", :, 1], and pd.IndexSlice["a":"c", :] for a slice with bounds. None for a slice call with keywords or unpacked arguments.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

pd.IndexSlice writes a selection over index levels with the colon that a slice has everywhere else. Write pd.IndexSlice[$NEW] in place of the tuple, which is the same object.

Browse the other rules of the pandas pack.