我正在處理一個包含字符串列表的列,并且想比較每行中的最后一個元素。如果最終元素不匹配,我想創建一個新變量,將第一個和最后一個元素連接起來,如下所示: element[0].element[-1]如果它們確實匹配,我想通過在列表中附加下一個元素來區分它們: element[0].element[-2].element[-1]我已將此專欄作為其原始格式的列表。這是數據框中原始變量的片段pandas:apple.banana.pearapple.starfruit.grapeapple.kiwi.orange.pearapple.durian.coconutName: original, Length: 4, dtype: stringmylist = df['original'].apply(lambda x: x.split('.'))我目前的名單:[apple, banana, pear][apple, starfruit, grape][apple, kiwi, orange, pear][apple, durian, coconut]期望的輸出:apple.banana.pearapple.grapeapple.orange.pearapple.coconut我不確定將其放入列表是否是最佳選擇,但我認為將每個部分作為一個元素進行訪問會更容易。情況可能并非如此。這是我試過的:l = 0j = l + 1for l in mylist: for j in mylist: if mylist[l][-1] == mylist[j][-1]: newvar = mylist[l][0] + '.' + mylist[l][-2] + '.' + mylist[l][-1] else: newvar = mylist[l][0] + '.' + mylist[l][-1]KeyError: "None of [Index(['apple', 'banana', 'pear'], dtype='object')] are in the [index]"非常感謝任何建議。
1 回答

長風秋雁
TA貢獻1757條經驗 獲得超7個贊
我們可以做的
s=df.original.str.split('.')
df['new']=np.where(s.str[-1].duplicated(keep=False),
s.str[0]+'.'+s.str[-2]+'.'+s.str[-1],
s.str[0]+'.'+s.str[-1])
df
Out[47]:
original new
0 apple.banana.pear apple.banana.pear
1 apple.starfruit.grape apple.grape
2 apple.kiwi.orange.pear apple.orange.pear
3 apple.durian.coconut apple.coconut
添加回答
舉報
0/150
提交
取消