str 包含 datetime64 pandas 的等价物

str contains equivalent for datetime64 pandas

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

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

日期类型是datetime64[ns]。我在检查类型之前尝试了 df = df[df['Date'].str.contains('2019')],它给出了 AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

有其他选择吗?

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

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

也许与 //

核对一下
(df.Date//10000).eq(2019)
Out[58]: 
0     True
1    False
2     True
3    False
4     True
Name: Date, dtype: bool

如果它是 datetime64[ns] 格式,您可以做一些简单的事情:

df=df[df.Date.dt.year==2019]