如何在Python中对数据框的特定行求和

我有一个数据帧A,我想对各行求和,它们的行索引值的数字大于或等于10.
如果这不可能,那么我也可以使用在2-3行中求和的代码.

import pandas as pd
import numpy as np
A = """
        Tier         Oct   Nov   Dec
    0   up to 2M     4     5     10
    1   5M           3     2     7
    2   10M          6     0     2
    3   15M          1     3     5
   """
tenplus = pd.Series(A(axis=0),index=A.columns[1:])

但这是整个表的总和.我可以做的一件事是从2-3行中构建另一个数据框并对其求和,但是我更喜欢学习最佳实践!

谢谢!

解决方法:

您可以使用普通切片索引来选择要求和的行:

print(df)
#        Tier  Oct  Nov  Dec
# 0  up to 2M    4    5   10
# 1        5M    3    2    7
# 2       10M    6    0    2
# 3       15M    1    3    5

# select the last two rows
print(df[2:4])
#   Tier  Oct  Nov  Dec
# 2  10M    6    0    2
# 3  15M    1    3    5

# sum over them
print(df[2:4].sum())
# Tier    10M15M
# Oct          7
# Nov          3
# Dec          7
# dtype: object

如您所见,对“层”列求和不会产生任何意义的结果,因为“求和”字符串只是将它们串联在一起.仅总结最后三列会更有意义:

# select the last two rows and the last 3 columns
print(df.loc[2:4, ['Oct', 'Nov', 'Dec']])
#    Oct  Nov  Dec
# 2    6    0    2
# 3    1    3    5

# sum over them
print(df.loc[2:4, ['Oct', 'Nov', 'Dec']].sum())
# Oct    7
# Nov    3
# Dec    7
# dtype: int64

# alternatively, use df.iloc[2:4, 1:] to select by column index rather than name

您可以阅读有关熊猫in the documentation here中索引工作原理的更多信息.

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...