我有一个数据帧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行构建另一个数据框架,并对它们求和,但我更喜欢学习最佳实践!
谢谢!
发布于 2015-11-14 09:12:45
您可以使用普通切片索引来选择要求和的行:
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列求和得到的结果毫无意义,因为" summing“字符串只是将它们连接起来。仅对最后三列求和会更有意义:
# 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中的工作原理。
发布于 2015-11-14 04:31:32
sum具有轴参数,请传递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: int64https://stackoverflow.com/questions/33700529
复制相似问题