Python Pandas – How to use Pandas DataFrame tail( ) function

PythonPandasServer Side ProgrammingProgramming

Write a Python code to find price column value between 30000 to 70000 and print the id and product columns of the last three rows from the products.csv file.

Download the products.csv file here.

Result for price column value between 30000 to 70000 and id and product columns last three rows are −

   id product
79 80 Truck
81 82 Bike
98 99 Truck

Solution 1

df = pd.read_csv('products.csv ')
  • Apply pandas slicing to access all rows of price column between 30000 to 50000 as,

df[df.iloc[:,4].between(30000,50000)

Save the above result to df1

  • Apply slicing to access last three rows of first two column as,

df1.iloc[-3:,0:2]

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.read_csv('products.csv ')
df1 = df[df.iloc[:,4].between(30000,50000)]
print(df1.iloc[-3:,0:2])

Output

   id product
79 80 Truck
81 82 Bike
98 99 Truck

Solution 2

df = pd.read_csv('products.csv ')
  • Apply condition to access all rows of price column between 30000 to 50000 as,

df[(df['price']>30000) & (df['price']<50000)]

Save the above result to df1

  • Filter from df1 to access last three rows of first two column as,

df1[['id','product']].tail(3)

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.read_csv('products.csv ')
df1 = df[(df['price']>30000) & (df['price']<50000)]
print(df1[['id','product']].tail(3))

Output

   id product
79 80 Truck
81 82 Bike
98 99 Truck
raja
Published on 27-Feb-2021 10:49:15
Advertisements