我有一個Pandas資料框,其中有一列名為col1,我想向資料框中添加一個新列,該列的值取決于col1每條記錄的內容。我試過這個:
d['new_column'] = 'CASE 1' if d['COL1'] == None else 'CASE 2' if d['COL1'] == 0 else 'CASE 3'
但我收到了這個錯誤:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
如何進行評估以正確設定新列的值?
uj5u.com熱心網友回復:
嘗試使用np.where. 對于這種情況,它高效且易于使用:
import numpy as np
df['new_column'] = np.where(d['COL1'].isnull(), 'CASE1',
np.where(d['COL1']==0, 'CASE 2', 'CASE 3'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/396534.html
上一篇:當用戶在輸入中添加文本時,在用戶輸入后添加文本的方法是什么?在Python中
下一篇:加載不同背景場景的錯誤
