Retrieve from a Python Pandas series with .loc and indexes: If you pass booleans, True means “return a value,” and False means “ignore it.”
Over my 30+ years teaching Python, I’ve included practice exercises in all of my courses. And when I started to teach Git and Pandas, I made sure to include practice exercises there, too. That’s because there’s no learning without practice. At least, there’s no effective learning. Frustration isn’t fun, but it’s a necessary part of…
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:
Pass a list to .loc on a Python Pandas series, and get a series back:
The index in a Python Pandas series feels like a dict keys. But the keys can repeat:
To retrieve from a Python Pandas series, you can use [] to retrieve items. But don’t! In a series, [] uses the index. In a data frame, [] uses the column names. Confusing! Besides, .loc does everything [] does, but with more options and flexibility.
You can set a Python Pandas series index with set_axis. This returns a new series with the new index applied: s.index # still Index([‘a’, ‘b’, ‘c’], dtype=’str’)