简体   繁体   中英

How to calculate the percentage of rows in pandas?

I would like to create a new row consisting of the percentage of the each column's ones and minus ones.

alldata_2.head()

Conditions          -1       1
NormalBlink1400     48      108
NormalBlink2000     74      124
NormalBlink3000     77      147
NormalBlink4000     67      150
NormalNoBlink1400   40      119

the two rows I want to add: perc_one = (one / one + minus_one)
perc_minus_one = (minus_one / one + minus_one)

import pandas as pd 

data = {'Conditions ': ['NormalBlink1400', 'NormalBlink2000', 'NormalBlink3000', 'NormalBlink4000','NormalNoBlink1400'], 
        '-1': [48, 74, 77, 67,40], 
        '1': [108, 124, 147, 150,119]} 

df = pd.DataFrame(data) 

df['perc_one '] = (df["1"] / (df["1"] + df["-1"]))
df["perc_minus_one"] = (df["-1"] / (df["1"] + df["-1"]))

Output:

df.head()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM