Home > Enterprise >  Read specific row with row name in excel in python
Read specific row with row name in excel in python

Time:08-15

I am working on a personal python project and in that I want to read a excel file which contains the following data. [1]: https://i.stack.imgur.com/yhFal.png (data is in this image)

And lets say I want to fetch the price of men plain tshirt Medium, that is 800 using python but because I am not much used with pandas or any other excel file reading module in python, I don't know how to do it.

CodePudding user response:

Using pandas you can access whatever data you like.

# read the Excel file and store into dataframe
df = pd.read_excel("test.xlsx")

# get a series (like a list) of all values in the "size" column
sizes = df["size"]

# return rows that match a certain value
df.loc[df['size'] == "Small"]

# change multiple values simultaneously 
# here we have a range of rows (0:4) and a couple column values
df.loc[0:4 ,['Name','size']] = ["Big Shirt", 'Extra Large']

# and you can use this to filter the data however you want
price = df.loc[(df['Name'].str.contains("Men plain tshirt")) & (df['size'].str.contains("Medium"))]

CodePudding user response:

I'm sure there's a more concise way to do it with other dataframe-related methods in pandas, but here's one way:

Read the excel file with

import pandas as pd
df = pd.read_excel("data.xlsx")

Then iterate through the rows until we find a match:

def get_shirt_price(shirt_name, shirt_size):
    for _,row in df.iterrows():
        if row["Name"] == shirt_name and row["size"] == shirt_size:
            return row["price"]
    raise Exception("Could not find matching shirt entry")
  • Related