简体   繁体   中英

How to get sum and count of specific column in pandas?

My dataframe looks like this:

df = pd.DataFrame({'percent':[0.5, 0.2, -0.2, 0.5 ],
                   'amt':[10, 5, -5, 10]})   
percent    amt
0.5         10
0.2         5  
-0.2        -5
0.5         10

I want to get the count of rows where percentage is ">0", percentage "<0" and the sum of amount column.

Desired results

percentage '>0' = 3
percentage '<0' = 1
amt = 20

I tried

df[df.percent > 0].count()
df[df.percent < 0].count()
df['amt'].sum()

But this is returning something else and not as my desired result of a single value.

This should work

print(df[df['percent']>0].shape[0])    #Rows with % > 0               
print(df[df['percent']<0].shape[0])    #Rows with % < 0               
print(df['amt'].sum())                 #Sum of amount

Output:

3
1
20

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