我有一個簡單的資料框,如下所示:
dict1 = {'student name':['A','B','C','D','E'],
'math':[0,9,0,6,7],
'Eng' :[0,6,7,8,9],
'Chemical':[0,4,5,7,8]
}
df = pd.DataFrame(dict1)
df2 = df.loc[(df[['math']]==0).any(1),'mark'].apply(lambda x: x['mark'] =='Fail')
我想創建一個新列 'mark' ,其中 'math' = 0 為這些行添加 'Fail',但是當運行代碼時,我得到了下面的錯誤。你能幫忙解決我的問題嗎?預期輸出:
student name math Eng Chemical mark
0 A 0 0 0 Fail
1 C 9 6 4 Pass
2 D 0 7 5 Fail
3 E 6 8 7 Pass
4 F 7 9 8 Pass
KeyError Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py:3621, in Index.get_loc(self, key, method, tolerance)
3620 try:
-> 3621 return self._engine.get_loc(casted_key)
3622 except KeyError as err:
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\_libs\index.pyx:136, in pandas._libs.index.IndexEngine.get_loc()
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\_libs\index.pyx:163, in pandas._libs.index.IndexEngine.get_loc()
File pandas\_libs\hashtable_class_helper.pxi:5198, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas\_libs\hashtable_class_helper.pxi:5206, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'mark'
uj5u.com熱心網友回復:
使用numpy.where:
import numpy as np
df2 = df.assign(mark=np.where(df['math'].eq(0),
'fail', 'pass'))
輸出:
student name math Eng Chemical mark
0 A 0 0 0 Fail
1 B 9 6 4 Pass
2 C 0 7 5 Fail
3 D 6 8 7 Pass
4 E 7 9 8 Pass
如果您想在任何主題使用中都為零時失敗:
cols = ['math', 'Eng', 'Chemical']
df2 = df.assign(mark=np.where(df[cols].eq(0).any(axis=1),
'Fail', 'Pass'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446229.html
