Want to check if a Python dict contains a key? Use “in” on the dict: ‘a’ in d # True‘x’ in d # False Searching in d.keys() is far slower: ‘a’ in d # 10 ns‘a’ in d.keys() # 29 ns (!)
Want to create a Python dict? You have options; which is fastest? – Literal, with {‘a’:10, ‘b’:20}: 37.8 ns– Invoke dict(a=10, b=20): 58.5 ns– Invoke dict on a list of tuples, dict([(‘a’, 10), (‘b’, 20)]): 103 ns– Comprehension, {c : ord(c) for c in ‘ab’}: 78 ns
Trying to use .loc to retrieve a slice in Python Pandas? If the index repeats, you need to sort it:
Retrieve from a Python Pandas data frame with .loc, which takes 2 arguments: 1. Row selector: index, list of indexes, or a mask index (i.e., booleans)2. Optional column selector: column name or a list of column names .loc uses [] and not (), so you can use slices!
Filtering a Python Pandas data frame by the index? Pandas 3 adds pd.col, removing lambda from our .loc expression. Before: Now: Note: You cannot use pd.col with a series, only a data frame.
To filter a Python Pandas data frame by rows, use the same syntax and rules as for series: The lambda still returns a boolean series. The expression can use any column from the data frame. Tomorrow: How Pandas 3 improves on this.
Why do I use loc+lambda to filter a Python Pandas series? 1. If earlier lines filter common values, later loc/lambda lines have less to filter — so queries run faster.2. It’s easier to build queries, one line at a time.3. No assignment means less to track and clean up.
Best filter method for a Python Pandas series? Use loc + lambda, thus filtering the series you got, not the global s:
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.