Skip to content
Advertisement

How can I print a statement in Python to show the results of a mathematical operation on a Pandas Dataframe?

So I’ve got a simple summary dataframe of sales by gender that goes:

JavaScript

All I want to do now is to return a line in Python that reads: The mean gap in the amount sold is 16.67%

This is simply 30 – 25 divided by 30, and multiplied by 100; and I want a % sign at the end.

I have tried:

JavaScript

Unfortunately this does not work. I get:

The mean gap in the amount sold is: 0 NaN 1 NaN Name: Sales, dtype: object %

Thoughts please? I am very much a beginner so sorry for such a basic query!

Advertisement

Answer

Append ["Sales"].iloc[0] to your filter expressions to obtain directly values for M and F, and then project these changes to the print() function, too:

JavaScript
JavaScript

The explanation:

  • df.loc[df['Gender'] == 'M'] is a dataframe;
  • selecting the "Sales" column by appending ["Sales"] you obtain a series (with only 1 element), and
  • by appending .iloc[0] you obtain the first (=the only one) element of that series.

Note:

You may use f-string (for Python 3.6+) or .format() method for adjusting your output, e.g.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement