Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

python - filters the row data and summs it to see if it can give the result with reduce() combined with filter()

Figure out the sum of "Dwell Time" between yellow rows, and the result is: https://i.stack.imgur.com/9G6zF.png

Is there a better way

question from:https://stackoverflow.com/questions/66058417/filters-the-row-data-and-summs-it-to-see-if-it-can-give-the-result-with-reduce

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If need sum values per each 2 values of level column create groups by compare level by Series.eq, add cumulative sum by Series.cumsum and replace rows with 2 by missing values in Series.mask. Then pass it to GroupBy.transform and for last rows only add another mask with Series.duplicated:

df = pd.DataFrame({'level':[2,3,2,1,3,2,1,3,5,3,1,2],
                    'dwell time':[1,1,1,1,2,1,2,0,2,3,4,1]})

m = df['level'].eq(2)
g = m.cumsum().mask(m)

df['dwell time 1 + 3'] = (df.groupby(g)['dwell time']
                            .transform('sum')
                            .mask(g.duplicated(keep='last')))

print (df)
    level  dwell time  dwell time 1 + 3
0       2           1               NaN
1       3           1               1.0
2       2           1               NaN
3       1           1               NaN
4       3           2               3.0
5       2           1               NaN
6       1           2               NaN
7       3           0               NaN
8       5           2               NaN
9       3           3               NaN
10      1           4              11.0
11      2           1               NaN

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...