我有一個這樣的數據集。df = pd.DataFrame({"A" :[1,1,3,4], "B": [1,3,2,2]})我想創建一個新列,如果 A = 1 & B =(1,3) 我使用,.loc則類型為 1 的 C ,我的代碼是df.loc[(df['A'] == 1)&(df['B'] == 1), 'C'] = 'type 1'df.loc[(df['A'] == 1)&(df['B'] == 3), 'C'] = 'type 1'上面的方法有效,但是當我使用時df.loc[(df['A'] == 1)&(df['B'] == (1,3)), 'C'] = 'type 1'什么也沒有發生,它沒有顯示錯誤,列也沒有更新。預期輸出是A B C1 1 type 11 3 type 13 2 Nan4 2 Nan還有其他辦法嗎?提前致謝
3 回答

臨摹微笑
TA貢獻1982條經驗 獲得超2個贊
使用numpy.where
:
In [1517]: import numpy as np
In [1518]: df['C'] = np.where(df.A.eq(1) & df.B.isin([1,3]), 'type 1', np.nan)
In [1519]: df
Out[1519]:?
? ?A? B? ? ? ?C
0? 1? 1? type 1
1? 1? 3? type 1
2? 3? 2? ? ?nan
3? 4? 2? ? ?nan

慕森王
TA貢獻1777條經驗 獲得超3個贊
其他方法可能是嘗試使用.eval
類似于此處的答案:
df.loc[df.eval('A?==1?and?B?in?[1,3]'),?'C']=?'type?1'
如果您想修復現有的代碼,您可以嘗試用以下命令分隔|
:
df.loc[(df['A']?==?1)&((df['B']?==1)?|?(df['B']?==3)),?'C']?=?'type?1'

繁星coding
TA貢獻1797條經驗 獲得超4個贊
這是一個可能的解決方案,除了 pandas 之外不使用任何庫:
df['C'] = pd.Series(index=range(len(df)), dtype='float') df['C'][df['A'] == 1 & df['B'].isin((1, 3))] = 'type 1'
添加回答
舉報
0/150
提交
取消