2017-08-11 53 views
1

根據下面的代碼編寫了一個二進制變量編碼問題。如果feature小於或等於30,我想變量metric爲1,否則爲0。當我運行這段代碼,我得到了以下錯誤:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().嘗試基於條件語句對二進制變量進行編碼

if df1.Feature <= 30: 
    df1.metric=1 
else: 
    df1.metric=0 
+0

我猜錯誤代碼行沒有發佈。我看不到'a'變量。 – danihp

+0

[系列的真值可能不明確。使用a.empty,a.bool(),a.item(),a.any()或a.all()](https://stackoverflow.com/questions/32699034/the-truth-value-of- a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any) – ppperry

+0

這讓我很困惑,沒有任何對象,我導入了我的庫(numpy/pandas )和數據並嘗試創建變量REC30PY – mitch

回答

0

你是作爲一個對象測試整個系列的真值。您可以使用np.where來測試每個元素。你的情況:

df1.loc[:, 'REC30PY'] = np.where(df1.velocity<=30, 1, 0) 

或者,得到的布爾值:

df1.loc[:, 'REC30PY'] = np.where(df1.velocity<=30, True, False) 
+0

可以確認以上作品,謝謝大家! – mitch

1

您可以通過astype布爾面具True轉換爲1False0

df1['REC30PY'] = (df1.velocity<=30).astype(int) 

而對於TrueFalse s:

df1['REC30PY'] = df1.velocity<=30