How to take column-slices of dataframe in pandas
To slice columns in a pandas DataFrame, use loc with column names or iloc with column indices. For label-based slicing:
For position-based slicing:
Both methods return columns B and C from the DataFrame df.
Selecting exactly what you need
When you don't need consecutive columns, select non-adjacent columns using a list:
This will appropriately select only the specified columns, like the precision of a trained sniper!
Slicing: inclusive is exclusive
Python slices are exclusive, but pandas' .loc and .iloc are inclusive of the last element:
The fossils of deprecated. features
Always keep your code young and vibrant! The old .ix indexer is deprecated. Let's stick to .loc and .iloc to avoid historical artifacts in our code.
Slice of Life
Don't fear the slice (function). It's the backbone of the sweet syntactic sugar that makes pandas slicing so readable:
Be flexible with reindexing
Reorder your life, as well as your DataFrame columns. Use reindexing to follow a new order that makes more sense:
Our new DataFrame now prioritizes Profits over other columns.
Know your extraction game
With large datasets, getting the data you need is like finding a needle in a haystack. Use iloc to ensure you're targeting the right haystack :
Slices without slippages
Tread carefully while slicing. A typo or index error can ruin your day. To avoid those, use the columns attribute of your dataframe:
This approach is bulletproof against typos and adjusts dynamically to column changes.
Was this article helpful?