how to select the last row with .loc pandas in python

To select the last row using the .loc accessor in pandas, you can use the [-1:] indexing notation. Here's an example:

main.py
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Select the last row using `.loc`
last_row = df.loc[-1:]

print(last_row)
170 chars
10 lines

This will output:

main.py
   A  B
2  3  6
16 chars
3 lines

Note that we use [-1:] instead of [-1] to get a DataFrame with a single row. If we used [-1], it would return a series instead.

gistlibby LogSnag