英文:
Remove elements of a list column based on condition
问题
我想要从一个pandas数据帧列中删除不包含下划线的列表元素。我该如何做?
w = pd.DataFrame({'Column A': ['Cell 1', 'Cell 2', 'Cell 3'], 'Column B': [['a_1', 'a'], ['b1', 'b2'], ['c_1', 'c_2', 'c3']]})
我想要的结果是:
Column A Column B
0 Cell 1 [a_1]
1 Cell 2 []
2 Cell 3 [c_1, c_2]
英文:
I'd like to remove elements of a list in a pandas dataframe column that does not contain an underscore. How can I do this?
w = pd.DataFrame({'Column A': ['Cell 1', 'Cell 2', 'Cell 3'], 'Column B': [['a_1', 'a'], ['b1', 'b2'], ['c_1','c_2', 'c3']]})
Of which I want my results to be:
Column A Column B
0 Cell 1 [a_1]
1 Cell 2 []
2 Cell 3 [c_1, c_2]
答案1
得分: 0
你可以explode列表并搜索匹配的值:
>>> w['Column B'].explode().loc[lambda x: x.str.contains('_')].tolist()
['a_1', 'c_1', 'c_2']
英文:
You can explode the list and search matching values:
>>> w['Column B'].explode().loc[lambda x: x.str.contains('_')].tolist()
['a_1', 'c_1', 'c_2']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论