我有這個資料,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]')
uj5u.com熱心網友回復:
沒錯,從您傳遞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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/532783.html
上一篇:這種資料截斷如何可能?
