2017-04-12 37 views
1

取下字符串作爲名單之列的特定字符串我有一個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] 

我怎麼能做到這一點嗎?

回答

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

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

你甚至可以使用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]