我有一个数据框,如下所示:

data={'time':['2021-01-01 22:00:12','2021-01-05 22:49:12','2021-01-06 21:00:00','2021-01-06 23:59:15','2021-01-07 05:00:55','2021-01-07 12:00:39'],
    'flag':['On','Off','On','Off','On','Off']}
df=pd.DataFrame(data)

我想要获得连续行之间的差异,这是我使用以下命令实现的:

df['diff']=pd.to_datetime(df['time'])-pd.to_datetime(df['time'].shift(1))

But there is calculation overhead here as there is no meaning for difference for every consecutive rows, I only want the difference whenever the flag goes to Off. Also, how to convert the difference into hours ? enter image description here

推荐答案

当旗帜熄灭时,掩盖差异

df['time'] = pd.to_datetime(df['time'])

mask = df['flag'].eq('Off') & df['flag'].shift().eq('On')
df['diff'] = df['time'].sub(df['time'].shift()).where(mask).dt.total_seconds() / 3600

                 time flag       diff
0 2021-01-01 22:00:12   On        NaN
1 2021-01-05 22:49:12  Off  96.816667
2 2021-01-06 21:00:00   On        NaN
3 2021-01-06 23:59:15  Off   2.987500
4 2021-01-07 05:00:55   On        NaN
5 2021-01-07 12:00:39  Off   6.995556

Python相关问答推荐

如何在句子之间添加空白但忽略链接?

判断两极中N(N 2)列水平是否相等

Python在通过Inbox调用时给出不同的响应

根据多列和一些条件创建新列

按照行主要蛇扫描顺序对点列表进行排序

覆盖Django rest响应,仅返回PK

具有多个选项的计数_匹配

如何在msgraph.GraphServiceClient上进行身份验证?

Pandas 都是(),但有一个门槛

如何过滤包含2个指定子字符串的收件箱列名?

如何在WSL2中更新Python到最新版本(3.12.2)?

如何将多进程池声明为变量并将其导入到另一个Python文件

如何设置视频语言时上传到YouTube与Python API客户端

递归访问嵌套字典中的元素值

driver. find_element无法通过class_name找到元素'""

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

在Python 3中,如何让客户端打开一个套接字到服务器,发送一行JSON编码的数据,读回一行JSON编码的数据,然后继续?

Polars asof在下一个可用日期加入

python panda ExcelWriter切换动态公式到数组公式

如何检测鼠标/键盘的空闲时间,而不是其他输入设备?