python - 当 Python 中不再显示唯一 ID 时标记大型数据集

标签 python python-3.x pandas dataframe count

这是一个非常具体的问题,但我有一个远远超过 1GB 的大数据集。该数据的格式如下:

Name         ID      OP Date      OP Hour        Gen         Heat
Jann         1       2001-01-01   1              10          0
Jann         1       2001-01-01   2              3           1
.
.
Jann         1       2001-01-01   24             13          3
Jann         2       2001-01-01   1              30          10
Jann         2       2001-01-01   3              32          11
.
.
Kay          1A      2002-01-01   1              0           12
Kay          1A      2002-01-01   2              2           22
.
.
.
.
.
Jann         1       2018-01-01   1              26          8
Jann         1       2018-01-01   2              32          21

有时,Name 会在某个时间出现在数据集开头 (2001-01-01) 和/或有时 Name 将不再出现在数据集在某个OP Date集中在一起。

此外,有时会出现名称,但只有该名称中的某个ID会消失。

我希望能够知道此数据中的某个NameID何时开始结束设置。

例如,Jann ID 1Jann ID 2 均从 OP Date 2001-01-01 开始,但 Jann ID 2 未显示在 OP Date 2018-01-01 中。此外,Kay ID 1A2002-01-01 开始,但在 2018-01-01 之前停止出现。

我想要的输出类似于数据框:

Name         ID      OP Start Date     OP EndDate
Jann         1       2001-01-01        2018-01-01
Jann         2       2001-01-01        SOME OP DATE
Kay          1A      2002-01-01        SOME OP DATE

有没有办法轻松做到这一点?

最佳答案

您可以尝试groupbyagg (或aggregate,它是相同的函数)在每个名称/的OP Date上应用firstlast身份证组合。这要求 df 按 OP 日期排序(因此使用 sort_values)

# convert to datetime first if not done already
df['OP Date'] = pd.to_datetime(df['OP Date'])

df.sort_values('OP Date').groupby(['Name', 'ID'])['OP Date'].agg(['first', 'last'])


             first       last
Name ID                      
Jann 1  2001-01-01 2018-01-01
     2  2001-01-01 2001-01-01
Kay  1A 2002-01-01 2002-01-01

关于python - 当 Python 中不再显示唯一 ID 时标记大型数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54560498/

相关文章:

python - 代码运行缓慢 - python 中的性能问题

python - 为什么 '12345' .count ('' ) 返回 6 而不是 5?

python - 使用 Python Pandas 对 csv 文件中的行进行排序

python - 使用request python下载txt文件

python 在单独的列中给出列名和写入值作为表

python - NetBeans 的 python 插件中的代码完成无法正常工作

python - 如何使用read_csv中的dtype将float转换为int?

python-3.x - 属性错误 : 'NoneType' object has no attribute 'drivername'

Python Pandas 如何根据相似的列加入 2 个或更多数据框

python - 除非在 10 分钟内,否则按前 15 分钟计算