简体   繁体   中英

How do I sum the range values I have selected in python

I have got the total number of value in the selected range. However, how do I sum the values in the range.

Currently, my coding that I have got is like this.

import pandas as pd;
data = pd.ExcelFile('~/Documents/FYP 2021/DATA/60.xlsx');
df = pd.read_excel(data)
print (pd.cut(df["Risk Level"],[0,0.25,0.5,0.75,1]).value_counts())

and the output;

(0.0, 0.25]    182
(0.25, 0.5]      4
(0.5, 0.75]      2
(0.75, 1.0]      1

So, how do I actually get the total sum number of 0.0-0.25, 0.25-0.5, 0.5-0.75 and 0.75-1.0.

I would like this:

df = pd.DataFrame({"num": pd.np.random.randint(0, 100, 10)})

df is:

0    90
1    24
2    65
3    71
4    36
5    85
6    83
7    39
8    90
9    29

df['interval'] = pd.cut(df.num, [0, 20, 50, 75, 100])
d1.groupby('interval').num.sum()

This will give you:

(0, 20]        0
(20, 50]     144
(50, 75]     169
(75, 100]    159

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