2017-04-11 52 views
0

我有一個目前看起來是這樣的一個數據幀:熊貓更新週末日期最近的業務

raw_data = {'AllDate':['2017-04-05','2017-04-06','2017-04-07','2017-04-08','2017-04-09']} 
import pandas as pd 
df = pd.DataFrame(raw_data,columns=['AllDate']) 
print df 

我想一個WeekDate列到這個數據幀添加比如如果在「AllDate」的date在週末,「WeekDate」專欄的日期從週五開始。如果日期屬於工作日,日期應該保持不變。

舉例來說,所產生的數據幀應該是這樣的:

raw_data = {'AllDate':['2017-04-05','2017-04-06','2017-04-07','2017-04-08','2017-04-09'],'WeekDate':['2017-04-05','2017-04-06','2017-04-07','2017-04-07','2017-04-07']} 
import pandas as pd 
df = pd.DataFrame(raw_data,columns=['AllDate','WeekDate']) 
print df 

任何想法如何,我可以做到這一點?

回答

0

嘗試:

import pandas as pd 
import time 

df = pd.DataFrame({ 
    'AllDate':['2017-04-05','2017-04-06','2017-04-07','2017-04-08','2017-04-09'] 
}) 
df['WeekDate'] = [ 
    x if x.weekday() not in [5,6] else None for x in pd.to_datetime(df['AllDate']) 
] 
print(df.ffill()) 
+0

爲什麼別人的 '非',並使用以前的值?在這種情況下不起作用: – sg91

+0

raw_data = {'AllDate':['2017-03-17','2017-04-16','2017-05-14','2017-06-18' ,'2017-07-18']}將pandas導入爲pd df = pd.DataFrame(raw_data,columns = ['AllDate'])print df – sg91

0

這個工作最好(增加張貼哲的答案):

import pandas as pd 
import time 
from datetime import datetime,timedelta 
df = pd.DataFrame({'AllDate':['2017-04-05','2017-04-06','2017-04-07','2017-04-08','2017-04-09']}) 
df['WeekDate'] = [x if x.weekday() not in [5,6] else x - timedelta(days = (x.weekday()-4)) for x in pd.to_datetime(df['AllDate'])] 
相關問題