我有一個如下所示的數(shù)據(jù)樣本(真實(shí)數(shù)據(jù)集有更多列):data = {'stringID':['AB CD Efdadasfd','RFDS EDSfdsadf dsa','FDSADFDSADFFDSA'],'IDct':[1,2,3]}
data = pd.DataFrame(data)
data['Index1'] = [[3],[7,9],[5,6,8]]
data['Index2'] = [[4],[10,13],[8,9,10]]僅當(dāng) IDct 數(shù)字大于 1 時,我才想獲取 Index1 和 Index2 列(列表)中的第二個元素(因?yàn)?IDct 數(shù)字表示列表中有多少個元素)。我正在嘗試以下答案,但都出現(xiàn)“列表索引超出范圍”的錯誤data['pos'] = np.where(data['IDct']>1, data.Index1.map(lambda x: x[1]),0)
data['pos1']= np.where(data['IDct']>1, data.Index2.map(lambda x: x[1]),0)或者data['pos'] = np.where(data['IDct']>1, [x[1] for x in data['Index1']],0)
data['pos1']= np.where(data['IDct']>1, [x[1] for x in data['Index2']],0)我應(yīng)該采取什么不同的做法?謝謝!
1 回答

Smart貓小萌
TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個贊
您可以嘗試使用 loc 來分配列。
data.loc[data['IDct'] > 1, 'pos'] = data.loc[data['IDct'] > 1]['Index1'].apply(lambda x: x[1]) data.loc[data['IDct'] > 1, 'pos1'] = data.loc[data['IDct'] > 1]['Index2'].apply(lambda x: x[1])
添加回答
舉報
0/150
提交
取消