如果满足条件,则将 list-series 中的 -n 元素追加到另一个 list-series

我有以下 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"]]})

其中我想将list2list2[-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”,所以也许需要正则表达式匹配。


忽然笑
浏览 232回答 1
1回答

收到一只叮咚

测试最后一个值转换为小写,如果匹配则添加到一个元素list,最后添加到原始列list1:s = dfo["list2"].apply(lambda x: [x[-1]] if x[-1].lower() == "test3" else [])dfo["list1_test3_added"] = dfo["list1"] + sprint (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]  
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python