从列表列中根据条件移除元素

huangapple go评论57阅读模式
英文:

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']

huangapple
  • 本文由 发表于 2023年3月31日 19:29:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定