𝗣𝗿𝗼𝗱𝘂𝗰𝘁 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆
🔶You are provided with a table named Products containing information about various products, including their names and prices. Write a code on Pandas to count number of products in each category based on its price into three categories below. Display the output in descending order of no of products.
🔶1- "Low Price" for products with a price less than 100
🔶2- "Medium Price" for products with a price between 100 and 500 (inclusive)
🔶3- "High Price" for products with a price greater than 500.
import pandas as pd
import numpy as np
products_df["category"] = np.where(
products_df['price'].between(0, 100, inclusive="neither"), "Low Price",
np.where(
products_df["price"].between(100, 500, inclusive="both"), "Medium Price",
np.where(
products_df["price"] > 500, "High Price", "Unknown"
)
)
)
products_df_ans= products_df.groupby("category").size().reset_index(name='no_of_products')
products_df_ans=products_df_ans.sort_values(by="no_of_products",ascending=False).reset_index(drop=True)
print(products_df_ans)
No comments:
Post a Comment