Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Pandas: pass column name as argument inte function

I have a DataFrame, df, with article numbers as columns (hundreds) and dates as index rows. df contains the number of sold items per product and day. This is a simplified example of it:

df = pd.DataFrame({'banana': [1, 8], 'apple': [3, 6]})

which outputs:

             banana   apple
2023-01-01   1        3
2023-01-02   8        6

I have a dictionary with prices:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

price_dict = {'banana': 10, 'apple': 100}

I’m trying to multiply the number of sold fruits with the price of that fruit for every given day by a function like this:

def get_sales(quantity, fruit):
    return price_dict[fruit] * quantity

and then I want to create a new DataFrame with the sales by calling that function, like this:

df_sales = df.apply(lambda x: get_sales(x, x.column)

expecting following outcome:

             banana   apple
2023-01-01   10       300
2023-01-02   80       600

However, I can’t figure out how I can pass the column name into the function. How can I use the name of the column in a dictionary, like in my example?

>Solution :

For pass columns names here use x.name:

df_sales = df.apply(lambda x: get_sales(x, x.name))

If need multiple by dictionary with keys by columns names simplier is:

df_sales = df.mul(price_dict)
#df_sales = df * price_dict
print (df_sales)
   banana  apple
0      10    300
1      80    600
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading