从pandas.DataFrame中的列中删除字符串列表中的某些字符串

时间:2017-04-12 20:50:50

标签: python pandas dataframe

我有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]

我该怎么办呢?

3 个答案:

答案 0 :(得分:2)

一个选项:使用apply方法循环浏览tag列中的项目;对于每个项目,使用列表推导来使用startswith方法基于前缀过滤字符串:

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

enter image description here

答案 1 :(得分:2)

您可以将函数应用于仅使用以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]

答案 2 :(得分:2)

你甚至可以在运算符

中使用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]
相关问题