Arithmetic operations across rows in pandas dataframe

Question:

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

Asked By: Ibashorun Ogunmola

||

Answers:

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", :]
Answered By: Paul H

here is one way to do it

df2=df.T
df2['3']=df2.iloc[1:,2]/df2.iloc[1:,0]
df2=df2.T
df2.iloc[3,0] = 'Gross Margin'
df2
    Metric          2012                   2013            2014     2015            2016
0   Revenue          116707394.0    133084076.0     143328982.0     151271526.0     181910977.0
1   Cost_of_Sales    -66538762.0    -76298147.0     -82099051.0     -83925957.0     -106583385.0
2   Gross_profit     501686320.0     56785929.0     612299310.0      67345569.0     75327592.0
3   Gross Margin        4.298668       0.426692        4.271985        0.445197     0.41409
Answered By: Naveed
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.