Turn a column in a Python Pandas data frame into an index with set_index: Remember, set_index returns a new data frame. It doesn’t change the original one. Turn multiple columns into a multi-index by passing a list:
Want to include a dynamic value in a multi-line Python string? That would require both an f-string and a triple-quoted string. Good news: Python supports this!
Want to include a newline in a Python string? Use \n: That’s fine for small strings. But for longer ones, use a triple-quoted string: BTW, the created strings are the same:
A classic Python mistake: What’s wrong with this code? The string uses ” as delimiters. But it also contains a ‘ inside. Solutions:
Want to read a non-text file with Python? Specify “rb”, for “read binary,” to avoid errors. What is t? A *byte* string, not a regular text string.
Python tip: Don’t write all 6 comparison methods! Define __eq__ and __lt__, then add @total_ordering: You get >, >=, <= for free!
Want to guarantee that no one can run “from .. import *” on your Python module? Include a non-existent name in the __all__ list: Using “from .. import *” on this module will result in an error!
Writing a Python module? Want to control which names are exported via “from .. import *”? Define __all__, a list of strings indicating which names will be exported via “import *”:
Using many names from a Python module? Import them all: Wait: This is usually a TERRIBLE idea! • Potential namespace collisions• Less readable code• Module upgrades affect globals in your program I know, it’s tempting — but don’t!
Python trick: 0 is falsy, 1 is truthy. Use this for even/odd checks: No need for “if n % 2 == 0” — just use the truthiness!