【发布时间】:2022-11-14 07:03:08
【问题描述】:
我有这个数据,dtype datetime64[ns]
df.date_month
Output:
0 2018-09-01
1 2018-09-01
2 2018-09-01
3 2018-09-01
4 2018-09-01
...
Name: date_month, Length: 4839993, dtype: datetime64[ns]
如果我运行一个 for 循环并添加 pd.Offset,代码就会运行。
for i in df.date_month[0:10]:
print(i + pd.DateOffset(months=12))
Output:
2019-09-01 00:00:00
2019-09-01 00:00:00
2019-09-01 00:00:00
2019-09-01 00:00:00
但是,如果我使用 unique(),代码会中断。
for i in df.date_month.unique():
print(i + pd.DateOffset(months=12))
Output:
UFuncTypeError Traceback (most recent call last)
<command-3708796390803054> in <module>
1 for i in df.date_month.unique():
----> 2 print(i + pd.DateOffset(months=12))
UFuncTypeError: ufunc 'add' cannot use operands with types dtype('<M8[ns]') and dtype('O')
有人可以帮我为什么会这样吗? unique() 是否以某种方式转换数据?
df.date_month.unique()
Output:
array(['2018-09-01T00:00:00.000000000', '2018-04-01T00:00:00.000000000',
'2018-12-01T00:00:00.000000000', '2018-11-01T00:00:00.000000000',
'2018-07-01T00:00:00.000000000', '2018-05-01T00:00:00.000000000',
'2018-06-01T00:00:00.000000000', '2018-10-01T00:00:00.000000000',
'2018-08-01T00:00:00.000000000'], dtype='datetime64[ns]')
【问题讨论】:
标签: python pandas datetime timestamp