July and August are often when people take a break or go on vacation. But for me, this summer has been super busy, full of writing and improving LernerPython based on feedback I’ve gotten from people around the world. And so, I’m here with some big changes I’m making at LernerPython World Headquarters: 1. AI…
My favorite way to apply multiple filters to a Python Pandas series? Method chaining calling loc 2x: But: This can break! Tomorrow, a better way.
When applying multiple filters to a Python Pandas series, it’s often best to use multiple lines: This is easier to read, write, and maintain.
Want to filter a Python Pandas series with two conditions? One option: Combine two boolean series with &. But careful: Put () around each boolean condition.
Retrieve selected items from a Python Pandas series by broadcasting a condition, then using it as a boolean (“mask”) index:
Retrieve from a Python Pandas series with .loc and indexes: If you pass booleans, True means “return a value,” and False means “ignore it.”
Apply an operator to a Python Pandas series, with a scalar value, *broadcasts*: Arithmetic is most obvious: s + 5 # [15, 25, 35]s ** 2 # [100, 400, 900] But comparisons work, too: s >= 20 # [False, True, True]
What’s the fastest way to retrieve the first 2 items from a Python Pandas series?
Using .loc to retrieve from a Python Pandas series is more convenient. But .iloc is faster: %timeit s.loc[‘a’] # 2.09 μs%timeit s.iloc[0] # 1.5 μs %timeit s.loc[[‘a’, ‘b’]] # 105 μs%timeit s.iloc[[0, 1]] # 26.4 μs
Retrieve from a Python Pandas series by position, rather than the index, with iloc: