TL;DR: If you teach Python, then you should check out course-setup (https://pypi.org/project/course-setup/) at PyPI! I’ve been teaching Python and Pandas for many years. And while I started my teaching career like many other instructors, with slides, I quickly discovered that it was better for my students — and for me! — to replace them with…
A Python Pandas column contains comma-separated values. How can you get the first of those? First, break each string into a list: Then use .str[0] to grab the first element from the resulting list:
Want to check whether a Python Pandas string series only contains digits? Use str.isdigit: This returns a boolean series, with df’s index. You can then convert the digit-containing strings to integers:
Want to retrieve a slice from a string column in your Python Pandas data frame? Use .str.slice:
Want to retrieve from a string column in your Python Pandas data frame? Use .str.get: But wait: You can use [], in place of .get:
Your Python Pandas data frame has a multi-index, and you want to remove one part — not return it to be a regular column? Add drop=True:
Your Python Pandas data frame has a multi-index? Return selected parts to columns with the “level” keyword argument:
Return a Python Pandas data frame’s index to a regular column with reset_index: • 1-column index? It’s now a regular column.• Multi-index? Its columns are all regular columns. reset_index returns a new data frame. It doesn’t modify the original.
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!