2017-08-16 56 views
1

我有包含像这样的字符串列表一列DF:只保留项目从列表中数据帧包含特定字符

'Name'  'Method' 
1 foo  ['car', 'truck', 'transportation::plane'] 
2 bar  ['car', 'transportation::helicopter', 'boat'] 
3 baz  ['transportation::car', 'helicopter', 'boat'] 

我只是想保持在该列表中的项目下包含方法“::”,使我得到这样的:

'Name'  'Method' 
1 foo  ['transportation::plane'] 
2 bar  ['transportation::helicopter'] 
3 baz  ['transportation::car'] 

我知道我可以做一个for循环每个列表进行迭代,然后使用列表理解,但我觉得必须有那并不是一个方法不涉及使用for循环。我试过以下内容

for j in range(len(df['Method'])): 
    df['Method'].iloc[j] = [x for x in df['Method'].iloc[j] if "::" in x] 

并且运行时间比我想要的要长得多。

回答

2

使用apply

In [220]: df.Method.apply(lambda x: [v for v in x if '::' in v]) 
Out[220]: 
1   [transportation::plane] 
2 [transportation::helicopter] 
3   [transportation::car] 

详细

In [222]: df['NMethod'] = df.Method.apply(lambda x: [v for v in x if '::' in v]) 

In [223]: df 
Out[223]: 
    Name         Method      NMethod 
1 foo  [car, truck, transportation::plane]  [transportation::plane] 
2 bar [car, transportation::helicopter, boat] [transportation::helicopter] 
3 baz [transportation::car, helicopter, boat]   [transportation::car] 

或者,使用filter

In [225]: df.Method.apply(lambda x: filter(lambda v: '::' in v, x)) 
Out[225]: 
1   [transportation::plane] 
2 [transportation::helicopter] 
3   [transportation::car] 
Name: Method, dtype: object 
0

,也可以使用str.contains

from itertools import compress 
import pandas as pd 

df['Method'].apply(lambda x :list(compress(x,pd.Series(x).str.contains('::').tolist()))) 
相关问题