Programming has climbed from soldered wires to assembly to Python, and each new layer of abstraction has let more people solve bigger problems. AI coding is the next layer, and it changes what we should teach.
My students used to ask if Python Pandas supports 3D data structures. Answer: No. Series are 1D and data frames are 2D. But… a multi-index effectively gives you more dimensions. You can then navigate the indexes with .loc and .xs.
To remove a level from a Python Pandas multi-index, use droplevel: – “level” kwarg takes an int or string– “axis” kwarg can be “index” or “columns” — or use 0 or 1, but I prefer the names Returned data frame has the same number of rows, but index might have duplicates.
What does a Python Pandas data frame’s multi-index look like? This:
Using xs on a multi-indexed Python Pandas data frame drops the named level — unless you use drop_level=False:
Using xs to retrieve from a Python Pandas multi-index? “level” takes an int or string: – int: The index level, with 0 the outermost– string: The level’s name — but not every level has one The name is clearer, but sometimes harder to type.
To retrieve all rows from a multi-indexed Python Pandas data frame or series based on the outermost index, use “loc”:
Using resample in Python Pandas? You’ll want a list of “offset aliases,” the codes that let you specify units. Some are surprising, such as “ME” and “MS” for “month end” and “month start”. They’re at: https://pandas.pydata.org/docs/user_guide/timeseries.html#offset-aliases
Slice an unsorted datetime index in Python Pandas, and you’ll likely get: KeyError: ‘Value based partial slicing on non-monotonic DatetimeIndexes with non-existing keys is not allowed.’ Why? If the dates are unsorted, where should Pandas start/stop? Solution: sort_index!
Want to select a chunk of time from a Python Pandas data frame? Make the datetime column the index, then use .loc and a slice to choose dates: