Home > other >  Pandas dataframe, max value where column value is greater than variable
Pandas dataframe, max value where column value is greater than variable

Time:08-09

I'm trying to get the name back from a dataframe based on if the cost of a product is less than the amount I have to spend. This is my dataframe with a list of products and their prices.

Dataframe example

I've tried:

def shopping(cash):
    x = df.loc[df['Cost'] <= cash, 'Name'].max()
    return x

But it's just returning nothing, any help would be appreciated

CodePudding user response:

Before running your function make sure that values in df['cash'] are of a number type (such as int or float).

df['Cost'] = df['Cost'].astype(float)

Why are you applying a max on the 'name' column? What do you mean by maximum name? I would suggest removing max() if you want the name of all such products.

CodePudding user response:

Pls check this code- If you spend $12 cash then you are checking for item which is close to $12 which can be bought. I think you forget running function shopping so output is not getting.Run the below code.

# Import pandas library
import pandas as pd
  
# initialize list of lists
data = [['banana', 10], ['tomato', 15], ['apple', 20]]
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Name', 'Cost'])
  
# print dataframe.
df

def shopping(cash):
    x = df.loc[df['Cost'] <= cash, 'Name'].max()
    return x
shopping(12)

Output-

banana
  • Related