简体   繁体   中英

How to multiply different indices in a row in Pandas DataFrame in Python?

produce.xlsx

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM