Skip to main content
 首页 » 编程设计

python之str 包含 datetime64 pandas 的等价物

2025年05月04日13me-sa

我有一堆数据如下,我只想要 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