gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:29:16 25 4
gpt4 key购买 nike

我有一个数据框 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

如您所见,对 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

您可以阅读更多有关索引在 pandas 中如何工作的信息 in the documentation here .

关于python - 如何在 Python 中对数据框的特定行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com