[英]sum of specific rows in a dataframe
df = pd.DataFrame({'Tissues':['a1','x2','y3','b','c1','v2','w3'], 'M':[1,2,3,4,5,6,7], 'F':[8,9,10,11,12,13,14]})
df.set_index('Tissues')
Out[64]:
M F
Tissues
a1 1 8
x2 2 9
y3 3 10
b 4 11
c1 5 12
v2 6 13
w3 7 14
rem = ['a1', 'b', 'c1']
I'd like to get a new row 'rem' that get sums of rows with indexes in the list rem
.我想获得一个新行“rem”,它获取列表
rem
带有索引的行的总和。
I can probably rename the indexes a1, b, c1 to 'rem', and then do groupby(df.index).sum()
, but I am not sure how to rename all indexes to rem
.我可能可以将索引 a1、b、c1 重命名为“rem”,然后执行
groupby(df.index).sum()
,但我不确定如何将所有索引重命名为rem
。
I don't think you need groupby我认为你不需要 groupby
df.loc[rem].sum()
M 10
F 31
or或者
df.loc[rem].sum(axis=1)
Tissues
a1 9
b 15
c1 17
Use .loc:使用 .loc:
df = df.set_index('Tissues')
df.loc['rem'] = df.loc[rem].sum()
print(df)
Output输出
M F
Tissues
a1 1 8
x2 2 9
y3 3 10
b 4 11
c1 5 12
v2 6 13
w3 7 14
rem 10 31
You can try你可以试试
df = df.set_index('Tissues')
x = pd.Series(df[df.index.isin(rem)].sum(), index=['M', 'F'], name="rem")
df.append(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.