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
Read data from products.csv file and assign to df
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
Read data from products.csv file and assign to df
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