Home > Software design >  calculate percentage row by row in pandas dataframe
calculate percentage row by row in pandas dataframe

Time:11-08

I have a dataframe, df, i want to calculate percentage by row for one of the rows and return 'No' in the other row.

A B C D
X 500 250 50.00
Y 980 700 71.42
A B C D E
X 500 250 50.00 70.08
Y 980 700 71.42 No

70.08% is got by dividing 50.00/71.42

CodePudding user response:

# shift by a row and divide the two values

df['E']=df['D'].div(df['D'].shift(-1)).fillna('No')
df
    A     B       C         D   E
0   X   500     250     50.00   0.700084
1   Y   980     700     71.42   No
  • Related