如果這是重復的,我深表歉意。我已經搜索了很長時間,但仍然得到錯誤:“TypeError:_select_dispatcher() 得到了一個意外的關鍵字引數 'na'”或“TypeError:condlist 中的無效條目 0:應該是布爾 ndarray”。
我有一個資料框:
data_1 = {'A': ['Emo/3', 'Emo/4', 'Emo/1','Emo/3', '','Emo/3', 'Emo/4', 'Emo/1','Emo/3', '', 'Neu/5', 'Neu/2','Neu/5', 'Neu/2'],
'Pos': ["repeat3", "repeat3", "repeat3", "repeat3", '',"repeat1", "repeat1", "repeat1", "repeat1", '', "repeat2", "repeat2","repeat2", "repeat2"],
'B': [0, 0, 0, 0, '', 1, 2, 3, 4, '', 4, 2, 3, 1],'C': [0, 2, 1, 3, '', 4, 2, 3, 1, '', 4, 2, 3, 1]}
df_1 = pd.DataFrame(data_1)
df_1
A Pos B C
0 Emo/3 repeat3 0 0
1 Emo/4 repeat3 0 2
2 Emo/1 repeat3 0 1
3 Emo/3 repeat3 0 3
4
5 Emo/3 repeat1 1 4
6 Emo/4 repeat1 2 2
7 Emo/1 repeat1 3 3
8 Emo/3 repeat1 4 1
9
10 Neu/5 repeat2 4 4
11 Neu/2 repeat2 2 2
12 Neu/5 repeat2 3 3
13 Neu/2 repeat2 1 1
我想根據 B 列和 C 列創建 D 列。如果滿足條件,則輸入一個數字,如果不滿足則留空。這是我的代碼:
conditions = [
df_1.loc[(df_1['B']==1)&(df_1['C']==1)],
df_1.loc[(df_1['B']==2)&(df_1['C']==1)],
df_1.loc[(df_1['B']==3)&(df_1['C']==1)],
]
choices = [1,1,0]
df_1['D'] = np.select(conditions, choices, default='')
謝謝!
uj5u.com熱心網友回復:
你不應該.loc在你的條件下使用。此外,在一列中混合字串和數字也不是一個好主意,因此您應該將默認值設定為NaN而不是''。
嘗試:
conditions = [(df_1['B']==1)&(df_1['C']==1),
(df_1['B']==2)&(df_1['C']==1),
(df_1['B']==3)&(df_1['C']==1)]
choices = [1,1,0]
df_1['D'] = np.select(conditions, choices, default=np.nan)
>>> df_1
A Pos B C D
0 Emo/3 repeat3 0 0 NaN
1 Emo/4 repeat3 0 2 NaN
2 Emo/1 repeat3 0 1 NaN
3 Emo/3 repeat3 0 3 NaN
4 NaN
5 Emo/3 repeat1 1 4 NaN
6 Emo/4 repeat1 2 2 NaN
7 Emo/1 repeat1 3 3 NaN
8 Emo/3 repeat1 4 1 NaN
9 NaN
10 Neu/5 repeat2 4 4 NaN
11 Neu/2 repeat2 2 2 NaN
12 Neu/5 repeat2 3 3 NaN
13 Neu/2 repeat2 1 1 1.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341061.html
上一篇:Numpy:如何以矢量化方式根據另一個陣列的索引獲取整數陣列切片的總和?
下一篇:如何只獲取不到兩年的日期?
