我有一只熊貓df。資料框是從 excel 中讀取的。shortdate資料框中的列包含日期。我想要做的是獲取上周日期,然后拉出df上周日期和今天日期之間的所有行。問題是dfexcel 檔案中的日期和日期格式不同,因此我無法正確比較它們。一個是時間戳,一個是型別日期。
在下面的例子中,我只是用一個已知的值df來測驗它是否有效。但它不起作用。它回傳一個空df值,因為shortdate列中不存在這些值。
主檔案
todays_date = datetime.today().date() #todays date
date_of_last_week = todays_date - timedelta(days=7) #this is last weeks date
print('last weeks date :', date_of_last_week)
print('last weeks type is :', type(date_of_last_week))
entry_1000 = df['shortdate'][1000]
print('1000 entry date is:',entry_1000)
print('1000 entry type is:', type(entry_1000))
print('1000 entry date just date is:',entry_1000.date())
print('1000 entry just date type is:', type(entry_1000.date()))
just_date = entry_1000.date()
print(df_eb.loc[df['shortdate'] == just_date])
結果:
last weeks date : 2021-10-15
last weeks type is : <class 'datetime.date'>
1000 entry date is: 2020-03-28 00:00:00
1000 entry type is: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
1000 entry date just date is: 2020-03-28
1000 entry just date type is: <class 'datetime.date'>
Empty DataFrame
Columns: [record, old record, Status, shortdate]
Index: []
uj5u.com熱心網友回復:
您可以使用以下代碼將shortdate列轉換為datetime資料型別
df.shortdate = df.shortdate.apply(lambda x: x.date())
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331638.html
上一篇:delonfieldfromvars(instance)從物件中洗掉屬性
下一篇:考慮使用items()進行迭代
