python - Pandas 从时间序列列中获取日期范围

标签 python pandas dataframe

我有一个看起来像这样的数据框:

id  ts  factor
A   2020-01-01  1
A   2020-01-02  1
A   2020-01-03  1
A   2020-01-04  1
A   2020-01-05  1
A   2020-01-06  10
A   2020-01-07  10
A   2020-01-08  10
A   2020-01-09  10
A   2020-01-10  10
A   2020-01-11  10
A   2020-01-12  10
A   2020-01-13  10
A   2020-01-14  10
A   2020-01-15  10
A   2020-01-16  10
A   2020-01-17  10
A   2020-01-18  1
A   2020-01-19  1
A   2020-01-20  1

我想要的输出是:

id  start_ts    end_ts  factor
A   2020-01-01  2020-01-05  1
A   2020-01-06  2020-01-17  10
A   2020-01-18  2020-01-20  1

到目前为止,我只能想到对因子进行分组,然后进行最小和最大操作,但这不适用于因子1

df.groupby(["factor"]).agg({'date' : [np.min, np.max]})

如何实现输出?

最佳答案

使用cumsumfactor的移位进行比较,找到factor block ,然后将其添加到groupby :

blocks = df['factor'].ne(df['factor'].shift()).cumsum()
df.groupby(['id','factor',blocks], sort=False)['ts'].agg(['min','max'])

输出:

                         min         max
id factor factor                        
A  1      1       2020-01-01  2020-01-05
   10     2       2020-01-06  2020-01-17
   1      3       2020-01-18  2020-01-20

关于python - Pandas 从时间序列列中获取日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72367364/

相关文章:

python - 在按钮中创建图像

python - 比较两个不同数据框 pandas 的列

python - 将大型数据帧(pandas)分割成 block (但在分组之后)

python - Pandas 按 2 列的条件按聚合数据框分组

r - 如何从不匹配的数据框中选择行?

Pandas 数据帧到 Spark 数据帧 "Can not merge type error"

python - 如何将 Nonetype 转换为 int 或 string?

python - 如何将 log base 2 与 GEKKO (Python) 一起使用

python - 替换数据框的多个特定列中的值

python - 在 Python Pandas 中,如何像 R dplyr mutate_each 一样使用