Arithmetic operations across rows in pandas dataframe

How do I perform an arithmetic operation across rows and columns for a data frame like the one shown below?

For example I want to calculate gross margin (gross profit/Revenue) – this is basically dividing one row by another row. I want to do this across all columns.
enter image description here

>Solution :

I think you need to restructure your dataframe a little bit to do this most effectively. If you transposed your dataframe such that Revenue, etc were columns and the years were the index, you could do:

df["gross_margin"] = df["Gross profit"] / df["Revenue"]

If you don’t want to make so many changes, you should at least set the metric as the index.

df = df.set_index("Metric")

And then you could:

gross_margin = df.loc["Gross profit", :] / df.loc["Revenue", :]

Leave a Reply