2016-09-05 51 views
2

我正在提取功能以查找工作日。我到目前爲止是這樣的:熊貓數據框,將值分配給星期幾。特徵提取

days = {0:'Mon', 1: 'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'} 
data['day_of_week'] = data['day_of_week'].apply(lambda x: days[x]) 
data['if_Weekday'] = np.where((data['day_of_week'] == 'Mon') | (data['day_of_week'] == 'Tues') | (data['day_of_week'] == 'Wed') | (data['day_of_week'] == 'Thurs') | (data['day_of_week'] == 'Friday'), '1', '0') 

該代碼將分配週一至週五爲1和週六,週日爲0。不過,我想爲工作日分配不同的值。例如,星期一= 1,星期二= 2,星期三= 3,星期四= 4,星期五= 5,星期六和星期日都應該等於0.

任何幫助將不勝感激。

回答

0

我認爲你可以使用mask

data = pd.DataFrame({'day_of_week':[0,1,2,3,4,5,6]}) 

#original column to new, add 1 
data['if_Weekday'] = data['day_of_week'] + 1 

#map days if necessary 
days = {0:'Mon', 1: 'Tues', 2:'Wed', 3:'Thurs', 4:'Fri', 5:'Sat', 6:'Sun'} 
data['day_of_week'] = data['day_of_week'].map(days) 

#correct weekend days 
data['if_Weekday'] = data['if_Weekday'].mask(data['if_Weekday'] >= 6, 0) 

print (data) 
    day_of_week if_Weekday 
0   Mon   1 
1  Tues   2 
2   Wed   3 
3  Thurs   4 
4   Fri   5 
5   Sat   0 
6   Sun   0 
+0

非常感謝您的回覆。這幫了我很多! – ALK

+0

如果我的或其他答案有幫助,請不要忘記[接受](http://meta.stackexchange.com/a/5235/295067)它。謝謝。不幸的是,只有一個答案可以接受。 – jezrael

0

OK我覺得這裏最簡單的辦法就是用np.where測試平日是否大於或等於5,如果是分配0,否則返回了平日值,並添加1它:

In [21]: 
df['is_weekday'] = np.where(df['weekday'] >= 5, 0, df['weekday'] + 1) 
df 
Out[21]: 
     dates weekday is_weekday 
0 2016-01-01  4   5 
1 2016-01-02  5   0 
2 2016-01-03  6   0 
3 2016-01-04  0   1 
4 2016-01-05  1   2 
5 2016-01-06  2   3 
6 2016-01-07  3   4 
7 2016-01-08  4   5 
8 2016-01-09  5   0 
9 2016-01-10  6   0 
+0

非常感謝您的回覆。但是,使用我最初的方法是否沒有辦法解決上述問題? – ALK

+0

查看修訂後的答案 – EdChum

相關問題