python数据框,获取事件开始和结束的列表

标签 python algorithm pandas

我有一个数据框和一个包含整数值的列(在我的例子中是 0 和 1)。指标是时间。当“区域”开始和结束时,我需要一个列表。我可以用 diff 然后循环来做到这一点。

示例:

import pandas as pd
df = pd.DataFrame(index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
df['test'] = pd.DataFrame([0, 1, 1, 1, 0, 0, 1, 1, 1, 0], index = df.index)

methodOfLooking = ((2,4),(7,9)) # something like this should be the result

关于获得结果的有效方法有什么想法吗?

最佳答案

您可以使用diffzip 获取开始和结束索引:

ix = df.test.diff().fillna(0)

In [74]: zip(df.index[ix==1],df.index[ix==-1]-1)
Out[74]: [(2, 4), (7, 9)]

关于python数据框,获取事件开始和结束的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33670905/

相关文章:

python - Y 中的 X 太多

algorithm - 更改二叉树的数字基数

algorithm - 高度为h的红黑树的最小节点数计算公式是什么?

python - 将 int64 转换为日期时间,格式为 %H :%M'

python - 像 Jupyter 一样使用 Atom

python - 有没有办法懒惰地解压无限生成器?

python - PIL jpeg,如何保留像素颜色

c++ - 线弯曲的简单算法

python - Pandas :来自聚合列的多条形图

python - Pandas 数据框中的颜色单元格