[英]Difficulty Creating column of Pandas Dataframe
我想基於現有列創建數據框的新列,但是我希望它以我數據框中的另一個現有列為條件。 以下代碼不起作用。 有人知道為什么嗎?
if CV['keyword'] == 0:
CV['left out'] = (CV['Prediction Numerator'] - (CV['Rate'] *10000))/(CV['Prediction Denominator'] - 10000)
else:
CV['left out'] = (CV['Prediction Numerator'] - (CV['Rate'] *10000 * 10))/(CV['Prediction Denominator'] - (10000 * 10))
我收到以下錯誤:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\bwei\Downloads\WinPython-64bit-2.7.9.4\python-2.7.9.amd64\lib\site-packages\pandas\core\generic.py", line 709, in __nonzero__
.format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
這是我數據框的前4列的摘要。
Zip keyword Prediction Numerator Prediction Denominator
0 01001 0 7650546.693200 40002.558782
1 01001 0 7650546.693200 40002.558782
2 01001 0 7650546.693200 40002.558782
3 01001 0 7650546.693200 40002.558782
4 01002 0 157.951741 0.718621
5 01002 0 157.951741 0.718621
6 01005 0 3600150.148240 20000.671431
7 01005 0 3600150.148240 20000.671431
8 01007 0 6932235.816260 30000.936191
9 01007 0 6932235.816260 30000.936191
10 01007 0 6932235.816260 30000.936191
謝謝,本
這應該工作:
CV.loc[CV['keyword']==0,'left out']=expression1
CV.loc[CV['keyword']!=0,'left out']=expression2
而不是CV['keyword'] == 0
,您應該'keyword' in CV.columns
使用'keyword' in CV.columns
來查看CV中是否有名為“ keyword”的列。
當你寫
if CV['keyword'] == 0:
那么CV['keyword']
是一列,將其與0進行比較會返回一個布爾序列。 您不能在這樣的序列上執行if
(該值將確定它是True
還是False
?),因此會出錯。
幸運的是, CV.columns
工作方式非常類似於Python列表,因此您可以使用它來檢查成員資格。
你想要的是
CV['left out'] = np.where(CV['keyword'] == 0,
(CV['Prediction Numerator'] - (CV['Rate'] *10000))/(CV['Prediction Denominator'] - 10000),
(CV['left out'] = (CV['Prediction Numerator'] - (CV['Rate'] * 10000 * 10))/(CV['Prediction Denominator'] - (10000 * ))
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.