从作为列的字符串列表中删除某些字符串Pandas.DataFram

2024-10-01 02:35:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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*字符串之外的所有字符串。在

所以我要用这样的话来结束:

^{pr2}$

请问我该怎么做?在


Tags: of字符串idgamedataframepandasindextag
3条回答

您可以将函数应用于tag系列,该系列只使用以'pset'开头的元素构造列表

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

# returns:
0           [pset3]
1           [pset4]
2           [pset6]
3    [pset8, pset5]
4           [pset4]

您甚至可以在operator中使用python

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

0           [pset3]
1           [pset4]
2           [pset6]
3    [pset8, pset5]
4           [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

相关问题 更多 >