在 pandas 数据框的给定列中仅对某些行求和 [英] Sum only certain rows in a given column of pandas dataframe

查看:83
本文介绍了在 pandas 数据框的给定列中仅对某些行求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以对5列熊猫数据框中的前310行求和,并使用以下命令获得整洁的摘要:

I can sum the first 310 rows in a 5 column pandas dataframe and get a tidy summary by using:

df.[0:310].sum

是否有一种简单的方法可以对自己选择的某些列中的前310行进行求和?我只是不知道如何在表达式中结合使用列选择和行切片选择.通过列名指定列是理想的,但是列索引也可以.

Is there an easy way whereby I can sum the first 310 rows in a certain column of my choosing? I just can't figure out how to combine a column selection and row slice selection in the expression. It would be ideal to specify the column by column name, but column index is fine too.

为了求和第5列的第310行,我尝试了

In an attempt to sum the 1st 310 rows of the 5th column, I tried

df.iloc[0:310, 4].sum

,但是从该列仅打印了310行.谢谢.

but just got a printout of 310 rows from that column. Thank you.

推荐答案

我认为需要

I think need DataFrame.iloc for select rows by positions with get_indexer for positions of columns by names:

#data borrowed from Akshay Nevrekar answer, but changed index values
data = {'x':[1,2,3,4,5], 
        'y':[2,5,7,9,11], 
        'z':[2,6,7,3,4]}
df=pd.DataFrame(data, index=list('abcde'))
print (df)
   x   y  z
a  1   2  2
b  2   5  6
c  3   7  7
d  4   9  3
e  5  11  4

a = df.iloc[:3, df.columns.get_indexer(['x','z'])].sum()

与什么相同:

a = df.iloc[:3, [0,2]].sum()

print (a)
x     6
z    15
dtype: int64

详细信息:

print (df.iloc[:3, df.columns.get_indexer(['x','z'])])
   x  z
a  1  2
b  2  6
c  3  7

如果只希望使用一列,请使用 get_loc 排名:

If want only one column use get_loc for position:

b = df.iloc[:3, df.columns.get_loc('x')].sum()

与什么相同:

b = df.iloc[:3, 0].sum()

print (b)
6

详细信息:

print (df.iloc[:3, df.columns.get_loc('x')])
a    1
b    2
c    3
Name: x, dtype: int64

这篇关于在 pandas 数据框的给定列中仅对某些行求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆