python - 试图获得最小值 date 并获得 TypeError: '<' not supported between 'datetime.datetime' 和 'int' 的实例

我正在从 excel 文件中读取

GA = pd.read_excel("file.xlsx", sheet_name=0, engine= "openpyxl")

数据类型为:

  • 电子邮件对象
  • Date 日期时间64[ns]
  • 名称对象

我只想获取电子邮件第一个 date 的行

例如:

  • A@gmail.com 2022 年 1 月 1 日
  • A@gmail.com 2022 年 2 月 1 日
  • B@gmail.com 2022 年 3 月 1 日 c

我只想得到

  • A@gmail.com 2022 年 1 月 1 日
  • B@gmail.com 2022 年 3 月 1 日 c

我试过 GA.groupby('email')['date'].min()

但我收到 TypeError: '<' not supported between 'datetime.datetime' 和 'int' 的实例

我尝试将 date 类型更改为对象,尝试添加 reset_index(),尝试使用 agg('min) 而不是 min(),尝试 GA.sort_values('date').groupby('email').tail(1) 但不断收到此错误,请帮助

回答1

我相信您的解决方案只是缺少 df['date'] = pd.to_datetime(df['date']) 才能正常工作,因此:

import pandas as pd
import numpy as np
data = {'email':  ['A@gmail.com', 'A@gmail.com', 'B@gmail.com'],
        'date': ['01/01/2022', '02/01/2022', '03/01/2022'],
        }
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
df.groupby('email')['date'].min()

输出是:

email
A@gmail.com   2022-01-01
B@gmail.com   2022-03-01
Name: date, dtype: datetime64[ns]

回答2

问题是,电子邮件有整数,而不是 date 谢谢你的时间

相似文章

随机推荐

最新文章