我有以下 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 回答
![?](http://img1.sycdn.imooc.com/54586425000103f602200220-100-100.jpg)
收到一只叮咚
TA贡献1821条经验 获得超4个赞
测试最后一个值转换为小写,如果匹配则添加到一个元素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]
添加回答
举报
0/150
提交
取消