python - Pandas ,通过列值的单调增加来拆分数据框

标签 python pandas numpy dataframe

我有一个巨大的数据框,其中包含一个名为 time 的日期时间类型列和另一个名为 dist 的浮点型列,数据框已根据时间和 dist 进行排序。 我想根据 dist 的单调递增将数据帧分成几个数据帧。

拆分

   dt                    dist
0  20160811 11:10        1.0
1  20160811 11:15        1.4
2  20160811 12:15        1.8
3  20160811 12:32        0.6
4  20160811 12:34        0.8
5  20160811 14:38        0.2

进入

   dt                    dist
0  20160811 11:10        1.0
1  20160811 11:15        1.4
2  20160811 12:15        1.8

   dt                    dist
0  20160811 12:32        0.6
1  20160811 12:34        0.8

   dt                    dist
0  20160811 14:38        0.2

最佳答案

您可以计算 dist 的差异向量列然后做一个cumsum()条件diff < 0 (每当 dist 从以前的值减少时,这会创建一个新的 ID)

df['id'] = (df.dist.diff() < 0).cumsum()

print(df)

#               dt  dist  id
#0  20160811 11:10   1.0   0
#1  20160811 11:15   1.4   0
#2  20160811 12:15   1.8   0
#3  20160811 12:32   0.6   1
#4  20160811 12:34   0.8   1
#5  20160811 14:38   0.2   2

for _, g in df.groupby((df.dist.diff() < 0).cumsum()):
    print(g)

#               dt  dist
#0  20160811 11:10   1.0
#1  20160811 11:15   1.4
#2  20160811 12:15   1.8
#               dt  dist
#3  20160811 12:32   0.6
#4  20160811 12:34   0.8
#               dt  dist
#5  20160811 14:38   0.2

关于python - Pandas ,通过列值的单调增加来拆分数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39680162/

相关文章:

python - numpy 保存/加载损坏数组

python - 从字典中输出python中的大矩阵

python - Matplotlib 和 Numpy - 创建日历热图

python - 如何用 `stdin=sys.stdin` 重现 `stdin=PIPE` ?

python - 让 Python 包以不同的名称安装自身

python - python pandas 转换 Unix 时间戳

python - 将 groupby 结果直接合并回数据框

python - read_csv() 中的 S3 阅读器是先将文件下载到磁盘还是使用流式传输?

使用 DataFrame 和 dict 获得加权总和的 Pythonic 方法

python - 在路径中使用变量的目录中创建文件夹(Python 3.6)