gpt4 book ai didi

python - 从字符串列表中删除某些字符串作为 pandas.DataFrame 中的列

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:15 25 4
gpt4 key购买 nike

我有一个pandas.DataFrame:

    index    question_id    tag
0 1858 [pset3, game-of-fifteen]
1 2409 [pset4]
2 4346 [pset6, cs50submit]
3 9139 [pset8, pset5, gradebook]
4 9631 [pset4, recover]

我需要从 tag 列中的字符串列表中删除除 pset* 字符串之外的所有字符串。

所以我需要这样结束:

    index    question_id    tag
0 1858 [pset3]
1 2409 [pset4]
2 4346 [pset6]
3 9139 [pset8, pset5]
4 9631 [pset4]

请问我该怎么做?

最佳答案

一种选择:使用apply方法循环遍历tag列中的项目;对于每个项目,使用列表理解来使用 startswith 方法根据前缀过滤字符串:

df['tag'] = df.tag.apply(lambda lst: [x for x in lst if x.startswith("pset")])
df

enter image description here

关于python - 从字符串列表中删除某些字符串作为 pandas.DataFrame 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43379418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com