我有这个数据示例:
0 1 2 3
2 Text1 1 1 5 5,00
3 Text2 8 4 0 0,00
4 Text3 1 3 0 2,00
5 SUM 6 0 0 7,00
6 Text1 1 1 0 10
7 Text2 8 4 0 0,00
8 Text3 1 3 0 0,00
8 Text4 1 3 0 2,02
9 SUM 6 0 0 20
我想计算最后一列的各行的总和,直到出现单词“ SUM” df[0]
,然后将此总和的结果分配给列表。例如:
第一总和应该是这样的:Text1 row + Text2 + Text3
= 5,00 + 0,00 + 2,00
-的总和df[:, -1]
的前面的行中df[0]=='SUM'
,然后将列表的第一个元素是['7,00']
则行中的单词之前的最后一列的总和SUM
中df[0]
:Text1+Text2+Text3+Text3
= 10+0+0+2,02
,然后将列表的第二元件是['12,02']
,整个列表现在看起来像这样:['7,00'],['12,02']
或['7,00','12,02']
最后,我想将整个列表与df.loc[(df[0] == 'SUM')]
df条件下的总数进行这样的计数吗?
给我一些提示或说明,我该怎么做以及是否可行。
采用:
#convert last column to numbers
df.iloc[:, -1] = df.iloc[:, -1].str.replace(',','.').astype(float)
#create groups with last value SUM
df.insert(0, 'g', df[0].eq('SUM').iloc[::-1].cumsum().iloc[::-1])
#sum values per groups with omit last value (SUM)
df.insert(0, 'new', df.iloc[:, -1].groupby(df['g']).transform(lambda x: x[:-1].sum()))
print (df)
new g 0 1 2 3 4
2 7.00 2 Text1 1 1 5 5.00
3 7.00 2 Text2 8 4 0 0.00
4 7.00 2 Text3 1 3 0 2.00
5 7.00 2 SUM 6 0 0 7.00
6 12.02 1 Text1 1 1 0 10.00
7 12.02 1 Text2 8 4 0 0.00
8 12.02 1 Text3 1 3 0 0.00
8 12.02 1 Text4 1 3 0 2.02
9 12.02 1 SUM 6 0 0 20.00
#compare values
df1 = df[df['new'].eq(df.iloc[:, -1]) & df[0].eq('SUM')]
print (df1)
new g 0 1 2 3 4
5 7.0 2 SUM 6 0 0 7.0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句