Home > database >  Applying function to multiple columns in pandas dataframe to make 1 new column
Applying function to multiple columns in pandas dataframe to make 1 new column

Time:10-03

fruits.xlsx

I'm trying to apply a function that:

  1. takes the value of each cell in a column divided by the mean of its respective column.
  2. Then create a column called ['Score'] that has the sum of each cell value in a row computed from step 1.

My code so far:

import pandas as pd
df = pd.DataFrame(pd.read_excel('fruits.xlsx'))
def func(column):
    out = df[column].values / df[column].mean()
    return out

Im really unsure of how to execute this with pandas properly.

CodePudding user response:

Try this one will calculate exactly what you need in one single line:

df['Score'] = df.apply(lambda x: sum([x[i]/df[i].mean() for i in df.columns]),axis=1)

CodePudding user response:

Can you post the output to:

df[0]

or

df.head()

This will help me answer your question properly.

  • Related