python - str 包含 datetime64 pandas 的等价物

标签 python pandas datetime contains

我有一堆数据如下,我只想要 2019 年的条目。

+----------+
|   Date   |
+----------+
| 20190329 |
| 20180331 |
| 20190331 |
| 20180331 |
| 20190401 |
+----------+

日期类型是 datetime64[ns]。我在检查类型之前尝试了 df = df[df['Date'].str.contains('2019')] 并给出了 AttributeError: Can only use .str accessor带有字符串值,在 pandas 中使用 np.object_ dtype

有替代方案吗?

最佳答案

看起来您有一列整数。在这种情况下,我推荐的解决方案是转换为日期时间,然后您将访问年份属性:

pd.to_datetime(df['Date'].astype(str)).dt.year == 2019  # you compare ints

0     True
1    False
2     True
3    False
4     True
Name: Date, dtype: bool

df[pd.to_datetime(df['Date'].astype(str)).dt.year == 2019]

       Date
0  20190329
2  20190331
4  20190401

另一种选择(稍微快一些,但我不喜欢这样,因为可能会被滥用)是对字符串进行切片并进行比较:

df['Date'].astype(str).str[:4] == '2019'  # you compare strings

0     True
1    False
2     True
3    False
4     True
Name: Date, dtype: bool

关于python - str 包含 datetime64 pandas 的等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56451892/

相关文章:

python - 为来自矩阵一列的每个线图创建图例条目

python - 多键字典初始化的代码更少

python - 使用lxml添加一个字符串作为子元素

python - 日期时间问题

python - Pandas - Python,删除基于日期列的行

python - date_parser 和 read_csv 的函数不起作用

java - 如何在 Java 中获取时间戳为 48962-08-06T23 :16:59. 000Z 的 Instant 对象

python - 如何向 django.forms 生成的表单添加删除按钮?

python - 找到相等的时间并逐渐添加一个常数

python - 看不懂这个定时while循环属性报错