python - Pandas 将数据帧与包含日期时间的系列进行比较

标签 python pandas datetime

我正在尝试将 Dataframe 与 Series 进行比较,以检查 df 中的某一行是否等于该系列,例如

import pandas as pd
import datetime as dt

d = pd.DataFrame([[1, dt.datetime(1990,12,10)],
                  [2, dt.datetime(1990,12,11)]])
s = d.loc[0].copy()

print(d == s)  # or d.gt(s) which should do the same

这会因以下错误而中断

TypeError: int() argument must be a string, a bytes-like object or a number, not 'Timestamp'

比较会产生预期的结果:

d.values == s.values
array([[ True,  True],
       [False, False]], dtype=bool)

此外,使用字符串不会引发此错误:

d = pd.DataFrame([[1, "a"], [2, "b"]])

s = d.loc[1].copy()

print(s == d)
#       0      1
#0   True   True
#1  False  False

这是 pandas 中的错误还是我做错了什么?

编辑:

我正在使用 python 3.6 和 pandas 0.20.3

我在 pandas github 上打开了一个问题: 17411

最佳答案

放弃

正如评论中提到的,(可能值得添加到问题中)这适用于字符串,所以我不明白为什么它不适用于日期时间

github 上的讨论 here表明关于日期时间与数字相比是否应该为假的争论正在进行中。

<小时/>

如果打印 ds,您将得到以下结果:

d:

   0          1
0  1 1990-12-10
1  2 1990-12-11

s:

0                      1
1    1990-12-10 00:00:00
Name: 0, dtype: object

在 s 中,左侧的数字 0,1 是索引(这是 s == d 比较的关键),因此您的代码正在比较 11,然后到 21990-12-10 00:00:00 - 这就是您收到错误的原因。

<小时/>

至于为什么这适用于值 - .values 返回没有索引的 numpy 数组,因此比较是在您期望的形状上完成的,而不是考虑索引。

关于python - Pandas 将数据帧与包含日期时间的系列进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45998145/

相关文章:

python-pandas : dealing with NaT type values in a date columns of pandas dataframe

mysql - 处理数据库中不同的日期时间格式?

python - 对字典进行排序但出现 "List Indices must be int, not tuple"错误

python - Django Python __init__() TypeError 'Default' 教程

python:使用正则表达式将文档字符串捕获为精确匹配

python - 每组的 pandas 计算

python - 根据索引是否存在于两个数据框中,选择并添加另一个数据框中的列值

python - 正则表达式匹配并提取长域

python - AttributeError : Can only use . 带有字符串值的 str 访问器,它在 pandas (Python) 中使用 np.object_ dtype

macos - 在 mac bash 上格式化修改文件的日期/时间?