2016-06-07 568 views
1

我有一個Dataframe並希望根據條件創建一個新列,如果滿足某個條件,則該值將來自另一列列,否則它需要爲零。 原始數據框是;基於python中另一列的值創建新列

df2 = pd.read_csv('C:\Users\ABC.csv') 
df2['Date'] = pd.to_datetime(df2['Date']) 
df2['Hour'] = df2.Date.dt.hour 
df2['Occupied'] = '' 
Date     Value Hour Occupied 
2016-02-02 21:00:00 0.6 21 
2016-02-02 22:00:00 0.4 22 
2016-02-02 23:00:00 0.4 23 
2016-02-03 00:00:00 0.3 0 
2016-02-03 01:00:00 0.2 1 
2016-02-03 02:00:00 0.2 2 
2016-02-03 03:00:00 0.1 3 
2016-02-03 04:00:00 0.2 4 
2016-02-03 05:00:00 0.1 5 
2016-02-03 06:00:00 0.4 6 

我想有在被佔領列df2.Value相同的值,如果df2.Hour大於或等於9,否則這些值將在佔用列零。我試過下面的代碼,但它不工作,因爲我想(它打印與df2.Value相同的值,而不考慮else語句);

for i in df2['Hour']: 
    if i >= 9: 
     df2['Occupied'] = df2.Value 
    else: 
     df2['Occupied'] = 0 

任何想法這是什麼問題?

回答

3

使用where與布爾條件,這將設置所有列值,而不是迭代逐行:

In [120]: 
df2['Occupied'] = df2['Value'].where(df2['Hour'] >= 9, 0) 
df2 

Out[120]: 
       Date Value Hour Occupied 
0 2016-02-02 21:00:00 0.6 21  0.6 
1 2016-02-02 22:00:00 0.4 22  0.4 
2 2016-02-02 23:00:00 0.4 23  0.4 
3 2016-02-03 00:00:00 0.3  0  0.0 
4 2016-02-03 01:00:00 0.2  1  0.0 
5 2016-02-03 02:00:00 0.2  2  0.0 
6 2016-02-03 03:00:00 0.1  3  0.0 
7 2016-02-03 04:00:00 0.2  4  0.0 
8 2016-02-03 05:00:00 0.1  5  0.0 
9 2016-02-03 06:00:00 0.4  6  0.0 
+0

感謝,這爲我工作。 – Muhammad