【问题标题】:Confusion over datetime64, timestamp and pd.DateOffset()对 datetime64、时间戳和 pd.DateOffset() 的混淆
【发布时间】: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


    【解决方案1】:

    没错,unique() 从您传递的Series 返回一个数组。见 --> https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html

    您很可能想使用 drop_duplicates() --> https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html

    IE。

    for i in df.drop_duplicates(subset=['date_month']).date_month:
        print(i + pd.DateOffset(months=12))
    

    【讨论】:

      猜你喜欢
      • 2015-02-07
      • 2014-06-10
      • 2018-10-19
      • 2012-04-07
      • 1970-01-01
      • 2020-08-20
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多