Python str包含datetime64的等效项
我有一堆如下的数据,我只想要2019个条目Python str包含datetime64的等效项,python,pandas,datetime,contains,Python,Pandas,Datetime,Contains,我有一堆如下的数据,我只想要2019个条目 +----------+ | Date | +----------+ | 20190329 | | 20180331 | | 20190331 | | 20180331 | | 20190401 | +----------+ 日期类型为datetime64[ns]。在检查类型之前,我尝试了df=df[df['Date'].str.contains'2019'],它给出了AttributeError:只能使用带字符串值的.str访问器,该访问器
+----------+
| Date |
+----------+
| 20190329 |
| 20180331 |
| 20190331 |
| 20180331 |
| 20190401 |
+----------+
日期类型为datetime64[ns]。在检查类型之前,我尝试了df=df[df['Date'].str.contains'2019'],它给出了AttributeError:只能使用带字符串值的.str访问器,该访问器在pandas中使用np.object udtype
还有别的选择吗 看起来您有一列整数。在本例中,我建议的解决方案是转换为datetime,然后访问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
看起来你有一列整数。在本例中,我建议的解决方案是转换为datetime,然后访问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
也许可以问问我//
也许可以问问我//
如果是datetime64[ns]格式,您可以执行以下简单操作:
df=df[df.Date.dt.year==2019]
如果是datetime64[ns]格式,您可以执行以下简单操作:
df=df[df.Date.dt.year==2019]
看起来像整数?首先尝试转换为字符串:df[df['Date'].astypestr.str[:4]='2019']您应该能够直接访问.year属性。看到整数了吗?首先尝试转换为字符串:df[df['Date'].astypestr.str[:4]='2019']您应该能够直接访问.year属性。见