2017-10-15 82 views
1

我在數據框中有一個'發佈日期'列,格式爲'2017-03-01'。該類型是<datetime64>[ns]。如果在'2017-03-31'到'2017-03-31'之後,並且所有其他值保持不變,我想要更改該值。有條件替換日期時間 - python

當我輸入df['Posting Date']>'2017-03-31'時,它可以正確顯示條件滿足的所有行。所以我猜日期過濾功能起作用。

然而,當我用numpy.where寫的條件,因爲這:

df['Posting Date'] = np.where(df['Posting Date']>'2017-03-31','2017-03-31,'df['Posting Date']) 

它incurrs一個invalid type promotion錯誤。我也嘗試過df.loc和相同的錯誤消息。

df.loc[df['Posting Date']>'2017-03-31','Posting Date']='2017-03-31' 

ValueError: invalid literal for int() with base 10: '2017-03-31'

我不知道爲何出現錯誤。我如何正確地更換日期?無論哪種方法工作都很好。

+0

我認爲你有一個剪切粘貼錯誤。 ''2017-03-31,'df ['發佈日期']'是語法錯誤。 (推測這個逗號應該在引號外面。)如果這實際上是正確的numpy語法,我的道歉。 –

+0

我還沒試過,但可以試試。 df ['Posting Date']。clip(upper = pd.Timestamp('2017-03-31')) – piRSquared

回答

0

及其因爲試圖取代與日期時間D型細胞列字符串日期時間,以便傳遞np.where即日期時間

df['Posting Date'] = np.where(df['Posting Date']>'2017-03-31',pd.to_datetime(['2017-03-31']),df['Posting Date']) 

輸出示例:

df = pd.DataFrame({'Posting Date': pd.to_datetime(['20-4-2017','20-4-2017','20-4-2017','20-3-2017','20-2-2017'])}) 
df['Posting Date'] = np.where(df['Posting Date']>'2017-03-31',pd.to_datetime(['2017-03-31']),df['Posting Date']) 

輸出:

 
Posting Date 
0 2017-03-31 
1 2017-03-31 
2 2017-03-31 
3 2017-03-20 
4 2017-02-20 

更好的一個@pirSquared發表評論使用剪輯即

df['Posting Date'] = df['Posting Date'].clip(upper=pd.Timestamp('2017-03-31')) 
+0

非常感謝!它完美地解決了我的問題。 –

+0

很高興幫助@LavenderPan – Dark