1 回答
TA贡献1824条经验 获得超6个赞
如果中的值key是唯一的并且需要按标签选择:
经柱CREATE INDEXkey通过set_index,然后通过选择DataFrame.loc:
#select return Series
print (df.set_index('key').loc['A'])
0 1
1-9 2
10-18 1
19-27 4
28-36 1
37-45 1
46-54 1
55-63 7
64-72 1
73-81 3
82-90 1
91-99 1
100 1
Name: A, dtype: int64
out = df.set_index('key').loc['A'].sum()
或者index先创建,然后再sum最后选择Series.ator Series.loc:
#sum return Series
print (df.set_index('key').sum(axis=1))
key
A 25
B 33
C 14
dtype: int64
out = df.set_index('key').sum(axis=1).at['A']
out = df.set_index('key').sum(axis=1)['A']
out = df.set_index('key').sum(axis=1).loc['A']
或者先过滤boolean indexing,然后过滤sum:
#filtering create one row DataFrame
print (df[df['key'] == 'A'])
key 0 1-9 10-18 19-27 28-36 37-45 46-54 55-63 64-72 73-81 82-90 \
1 A 1 2 1 4 1 1 1 7 1 3 1
91-99 100
1 1 1
out = df[df['key'] == 'A'].sum(axis=1).item()
如果key应复制值并需要按标签选择:
print (df)
key 0 1-9 10-18 19-27 28-36 37-45 46-54 55-63 64-72 73-81 82-90 \
1 A 1 2 1 4 1 1 1 7 1 3 1
2 A 3 1 1 1 6 1 1 1 7 1 8
3 C 1 1 2 1 1 1 1 1 1 1 1
91-99 100
1 1 1
2 1 1
3 1 1
首先可以将过滤后的值转换为 numpy 数组values,然后sum使用2d array:
out = df.set_index('key').loc['A'].values.sum()
双重sum- 第一次sum创建Series和第二次sum返回标量:
out = df.set_index('key').loc['A'].sum().sum()
out = df.set_index('key').sum(axis=1).at['A'].sum()
如果需要按职位选择:
使用DataFrame.iloc或Series.iat, Series.iloc:
out = df.set_index('key').iloc[0].sum()
out = df.set_index('key').sum(axis=1).iat[0]
out = df.set_index('key').sum(axis=1).iloc[0]
添加回答
举报