【问题标题】:find max-min values for one column based on another根据另一列查找一列的最大最小值
【发布时间】:2021-07-25 07:56:05
【问题描述】:

我有一个看起来像这样的数据集。

datetime                    id
2020-01-22 11:57:09.286 UTC 5
2020-01-22 11:57:02.303 UTC 6
2020-01-22 11:59:02.303 UTC 5

ID 不是唯一的,并且会给出不同的日期时间值。比方说:

持续时间 = max(datetime)-min(datetime)。

我想计算持续时间 max(datetime)-min(datetime) 小于 2 秒的 id​​。所以,例如我会输出:

count = 1

因为 id 5。然后,我想创建一个新数据集,其中只包含每个唯一 id 的 min(datetime) 值的那些行。因此,新数据集将包含第一行但不包含第三行。最终的数据集不应有任何重复的 id。

datetime                    id
2020-01-22 11:57:09.286 UTC 5
2020-01-22 11:57:02.303 UTC 6

我该怎么做?

P.S:我提供的数据集可能不是一个很好的例子,因为条件是 2 秒,但这里是以分钟为单位的

【问题讨论】:

  • 您应该发布原始数据帧,根据该数据帧导出例外输出。不可能进行逆向工程
  • 那是原始数据框,我需要这个@anky 的输出
  • 你能看到编辑吗? @anky

标签: python pandas dataframe datetime data-analysis


【解决方案1】:

你想要这个吗? :

df.datetime = pd.to_datetime(df.datetime)
c = 0
def count(x):
    global c
    x = x.sort_values('datetime')
    if len(x) > 1:
        diff = (x.iloc[-1]['datetime'] - x.iloc[0]['datetime'])
        if diff < timedelta(seconds=2):
            c += 1
            return x.head(1)

new_df = df.groupby('id').apply(count).reset_index(drop=True)

现在,如果您打印 c,它将显示在这种情况下计数为 1,new_df 将保存最终数据帧。

【讨论】:

  • 你能解释一下吗?我在哪里应用
  • @Jbd 更新了我的答案
  • 它现在给了我TypeError: unsupported operand type(s) for -: 'str' and 'str'。另外,你能解释一下x.iloc[-1]['datetime'] - x.iloc[0]['datetime'] 在做什么吗?
  • 你需要转换日期时间列的dtype
  • 你确定你想要 diff
猜你喜欢
  • 2021-05-25
  • 2021-05-17
  • 2022-01-23
  • 2020-08-09
  • 2012-05-06
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2014-10-05
相关资源
最近更新 更多