2015-11-13 37 views
1

我有一个数据框A,我想总结其行索引值大于或等于10的行。 如果这是不可能的,我可以在代码中生活2-3行。如何在Python中总结某个数据框的某一行

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行构建另一个数据框,然后结束它们,但我更愿意学习最佳实践!

谢谢!

+0

你的数据是一个可怕的格式,使'层'数值不知何故 – reptilicus

回答

1

您可以正常使用切片索引来选择要求和行:

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 

为y你可以看到,总结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是如何工作的。

0

总和具有轴线的说法,通过轴= 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 
+0

谢谢,但我想总结行而不是列。我已经添加了“轴= 0”的参数,但事情是我只想要第2行和第3行的总和。 – Ana

+0

@Ana这就是上述总结行......我无法理解你的其余部分'再说一遍。 –

相关问题