5 Pandas Tricks You Should Start Using in 2021
Start using Pandas the way it is intended to be used. Use these 5 tricks to improve pandas code.
--
If you ever worked with pandas, you’re most probably familiar with the richness of pandas library. Pandas enables us to achieve the same goal in multiple ways by using different functions.
The downside of this “richness” is that many of us learned the wrong approach which is hacky, error-prone and might even be deprecated in the future.
In this article, I show 5 pandas tips that will show you the proper way of performing basic operations with pandas.
Intro
Before we start, let’s create a sample DataFrame on which these tips are based:
import pandas as pddf = pd.DataFrame({"col1": ["A0", "A1", "A0", "A2", "A0", "A1"]})
1. How to retrieve a column value from a Dataframe
There are two ways of retrieving column values from a DataFrame:
- based on integer-location indexing (iloc),
- based on the label indexing (loc).
To retrieve the first column value for the col1 column (integer-location indexing):
df.iloc[0].col1# output: 'A0'
To retrieve the last column value:
df.iloc[-1].col1# output: ‘A1’
You can also retrieve a column value with the label. By default, pandas DataFrame has indices from 0 to n, where n is the number of rows in a DataFrame.
df.loc[1, “col1”]# output: ‘A1’
See pandas documentation to learn more about loc and iloc functions.