python - 过滤熊猫数据框,其中字段应该是时间戳,但 info() 显示非空对象
问题描述
我有一个数据框,我试图将其推送到数据库中,但我收到一条错误消息,表明我的主键约束被违反:
ecom.to_sql('ecom',
con = engine,
schema = 'ga_shop',
index = False,
if_exists = 'append')
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "ecom_pk"
DETAIL: Key (product_name, dimension3, dimension1)=(Apples, 2019-10-29 19:12:58.83+00, 1572376787423.pgp5jcd7) already exists.
我想过滤数据框 ecom 以查看这些重复的行,但我无法:
ecom[(ecom['dimension3'] == '2019-10-29 19:12:58.83+00')]
返回一个空的数据框。
ecom.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 82 entries, 14014 to 15002
Data columns (total 15 columns):
dimension1 82 non-null object
dimension3 82 non-null object
product_name 82 non-null object
ecom.head()
dimension1 dimension3 ... item_revenue sampling
0 1572337407387.0epe8tn 2019-10-29T04:20:08.119-04:00 ... 0.0 False
1 1572337407387.0epe8tn 2019-10-29T04:20:08.119-04:00 ... 0.0 False
2 1572337407387.0epe8tn 2019-10-29T04:20:08.119-04:00 ... 0.0 False
3 1572337407387.0epe8tn 2019-10-29T04:20:08.119-04:00 ... 0.0 False
4 1572337407387.0epe8tn 2019-10-29T04:20:08.119-04:00 ... 0.0 False
字段维度 3 是我从 API 中检索到的 iso 时间戳,但我不清楚 pandas 是如何存储它的,因为当我检查时它显示“82 non null object”ecom.info()
如何过滤维度 3(时间戳)以匹配错误消息的时间戳,以便我可以看到那些重复项?
解决方案
不幸的是,您必须在使用 过滤之前转换为日期时间utc=True
,因为有不同的时区:
date = pd.to_datetime('2019-10-29 19:12:58.83+00', utc=True)
df = ecom[pd.to_datetime(ecom['dimension3'], utc=True) == date]
另一种解决方案应该是只转换字符串:
print (ecom)
dimension1 dimension3 item_revenue \
0 1572337407387.0epe8tn 2019-10-29 04:20:08.119000-04:00 0.0
1 1572337407387.0epe8tn 2019-10-29 04:20:08.119000-04:00 0.0
2 1572337407387.0epe8tn 2019-10-29 04:20:08.119000-04:00 0.0
3 1572337407387.0epe8tn 2019-10-29 04:20:08.119000-04:00 0.0
4 1572337407387.0epe8tn 2019-10-29 19:12:58.830000+00:00 0.0
sampling
0 False
1 False
2 False
3 False
4 False <-changed date
print (type(ecom['dimension3'].iat[0]))
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
df = ecom[ecom['dimension3'] == pd.to_datetime('2019-10-29 19:12:58.83+00')]
print (df)
dimension1 dimension3 item_revenue \
4 1572337407387.0epe8tn 2019-10-29 19:12:58.830000+00:00 0.0
sampling
4 False
推荐阅读
- python - 按值对字典进行排序
- c# - 手机上的Unity鼠标输入
- android - CSS 媒体查询在移动设备上不起作用
- java - 感知散列 (pHash) 图像颜色 vs 灰度 vs 阈值,这是最佳输入源
- python - AWS Lambda 函数可以从 python 文件中调用另一个普通的 python 函数吗?
- haskell - 如何在 optparse-applicative 中重写 --help 标志输出
- javascript - 硬重载真的适用于 location.reload(true) 吗?
- javascript - 是否可以使用纯 JavaScript 访问 Angular *ngFor 的对象值?
- angular - 如何将数据从 API 加载到输入字段?
- python - 如何使用 matplotlib 执行条件区域绘图?