Im trying to create a function called get_total_produce that takes a column value from 'Name' and multiplies the values of 'Fruit' & 'Vegetables' in that row to return the total number of produce. How can I do do this with Pandas?
Current Code
import pandas as pd
df = pd.DataFrame(pd.read_excel('Produce.xlsx'))
Input for desired output
get_total_produce('Kroger')
Desired Output
280
CodePudding user response:
You can try something like the code below with pandas.Series.mul
:
def get_total_produce(name):
fruits_val = df[df['Name'] == name]['Fruits']
vegetables_val = df[df['Name'] == name]['Vegetables']
result = fruits_val.mul(vegetables_val).iloc[0]
return result
Or with pandas.DataFrame.prod
:
def get_total_produce(name):
filt_df = df.loc[df['Name'] == name, ['Fruits', 'Vegetables']]
result = filt_df.prod(axis=1).iloc[0]
return result
# Output :
get_total_produce('Kroger')
280