[英]how do I perform the explained operation in pandas?
this is my df这是我的df
idx = pd.date_range('2020-01-01',periods=26,freq='D')
vals = [0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,1,0,0,0,1,1]
pd.DataFrame(vals,index=idx)
what I need to know is what periods the values turn 1. so this particular case it turns 1 for the following period (and the output I want to see)我需要知道的是值在什么时期变为 1。所以这个特殊情况在接下来的时期变为 1(以及我想看到的 output)
2020-01-04:2020-01-07
2020-01-14:2020-01-18
2020-01-21:2020-01-21
2020-01-25:2020-01-26
thanks谢谢
We can group
the index
of the dataframe on the sequential blocks of 1's
and aggreagte using first
and last
to calculate the periods where the value turns/stays 1
.我们可以将 dataframe 的index
group
到1's
连续块上,并使用first
和last
聚合来计算值变为/保持1
的周期。
m = df[0].eq(1)
m[m].index.to_series().groupby((~m).cumsum()).agg(['first', 'last'])
first last
0
3 2020-01-04 2020-01-07
9 2020-01-14 2020-01-18
11 2020-01-21 2020-01-21
14 2020-01-25 2020-01-26
With itertools.groupby() .使用itertools.groupby() 。
import itertools
import operator
for k, g in itertools.groupby(enumerate(idx), lambda t: vals[t[0]]):
if k == 1:
days = list(map(operator.itemgetter(1), g))
print(days[0], days[-1])
2020-01-04 00:00:00 2020-01-07 00:00:00
2020-01-14 00:00:00 2020-01-18 00:00:00
2020-01-21 00:00:00 2020-01-21 00:00:00
2020-01-25 00:00:00 2020-01-26 00:00:00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.