如何在Python中对数据帧的某行求和

2024-05-19 05:21:42 发布

您现在位置: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行构建另一个数据帧并对其进行sume,但我更喜欢学习最佳实践!

谢谢!


Tags: to数据代码importnumpypandasasnp
2条回答

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

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

如您所见,对Tier列求和会产生无意义的结果,因为“求和”字符串只是将它们连接起来。仅对最后三列求和更有意义:

# 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中索引工作原理的更多信息。

sum有一个axis参数,传递axis=1对行求和:

In [11]: df
Out[11]:
       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

In [12]: df.sum(axis=1)
Out[12]:
0    19
1    12
2     8
3     9
dtype: int64

注意:这将丢弃非数值列,您可以在求和之前显式筛选这些列:

In [13]: df[['Oct', 'Nov', 'Dec']].sum(axis=1)
Out[13]:
0    19
1    12
2     8
3     9
dtype: int64

相关问题 更多 >

    热门问题