Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas divide one row by another and output to another row in the same dataframe

Tags:

python

pandas

For a Dataframe such as:

      dt
                COL000  COL001
      STK_ID                
      Rowname1  2  2
      Rowname2  1  4
      Rowname3  1  1

What's the easiest way to append to the same data frame the result of dividing Row1 by Row2? i.e. the desired outcome is:

                COL000  COL001
      STK_ID                
      Rowname1  2  2
      Rowname2  1  4
      Rowname3  1  1
      Newrow    2  0.5

Sorry if this is a simple question, I'm slowly getting to grips with pandas from an R background.

Thanks in advance!!!

like image 615
dvanic Avatar asked Sep 25 '14 15:09

dvanic


People also ask

How do you split a row in a data frame?

We can use the iloc() function to slice DataFrames into smaller DataFrames. The iloc() function allows us to access elements based on the index of rows and columns. Using this function, we can split a DataFrame based on rows or columns.

How do you divide two values in Pandas?

The simple division (/) operator is the first way to divide two columns. You will split the First Column with the other columns here. This is the simplest method of dividing two columns in Pandas. We will import Pandas and take at least two columns while declaring the variables.

How do you do division in Pandas?

In the pandas series constructor, the div() or divide() method is used to perform element-wise floating division operation between the two series objects or between a series and a scalar. The method returns a series with resultant floating division values.

What does diff () do in Pandas?

Pandas DataFrame diff() Method The diff() method returns a DataFrame with the difference between the values for each row and, by default, the previous row. Which row to compare with can be specified with the periods parameter.


2 Answers

The code below will create a new row with index d which is formed from dividing rows a and b.

import pandas as pd


df = pd.DataFrame(data={'x':[1,2,3], 'y':[4,5,6]}, index=['a', 'b', 'c'])

df.loc['d'] = df.loc['a'] / df.loc['b']

print(df)
#      x    y
# a  1.0  4.0
# b  2.0  5.0
# c  3.0  6.0
# d  0.5  0.8
like image 126
Ffisegydd Avatar answered Oct 10 '22 19:10

Ffisegydd


in order to access the first two rows without caring about the index, you can use:

df.loc['newrow'] = df.iloc[0] / df.iloc[1]

then just follow @Ffisegydd's solution...

in addition, if you want to append multiple rows, use the pd.DataFrame.append function.

like image 33
acushner Avatar answered Oct 10 '22 17:10

acushner