亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果滿足條件,則將 list-series 中的 -n 元素追加到另一個 list-series

如果滿足條件,則將 list-series 中的 -n 元素追加到另一個 list-series

忽然笑 2023-09-19 14:08:31
我有以下 DF(具有硬編碼的所需結果)dfo = pd.DataFrame({"list1": [["test1", "test2"], ["test1", "test2", "test3"], ["test1", "test2"]],                      "list2": [["notatest", "test3"], ["notatest"], ["notatest", "Test3"]],                                         "desired": [["test1", "test2", "test3"], ["test1", "test2", "test3"], ["test1", "test2", "Test3"]]})其中我想將list2( list2[-1]) 的最后一個元素添加/附加到list1if it == "test3"。嘗試了以下方法沒有效果:dfo["list1_test3_added"] = dfo["list1"].apply(lambda x: x.append([i for i in x["list2"][-1] if i == "test3"]))也可能是這樣的情況,在某些時候有人失去了理智,它不是“test3”而是“Test3”,所以也許需要正則表達式匹配。
查看完整描述

1 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

測試最后一個值轉換為小寫,如果匹配則添加到一個元素list,最后添加到原始列list1:


s = dfo["list2"].apply(lambda x: [x[-1]] if x[-1].lower() == "test3" else [])

dfo["list1_test3_added"] = dfo["list1"] + s

print (dfo)

                   list1              list2                desired  \

0         [test1, test2]  [notatest, test3]  [test1, test2, test3]   

1  [test1, test2, test3]         [notatest]  [test1, test2, test3]   

2         [test1, test2]  [notatest, Test3]  [test1, test2, Test3]   


       list1_test3_added  

0  [test1, test2, test3]  

1  [test1, test2, test3]  

2  [test1, test2, Test3]  


查看完整回答
反對 回復 2023-09-19
  • 1 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號