Python 仅保留包含特定字符的数据框中列表中的项目
我有一个df,其中一列包含字符串列表,如下所示:Python 仅保留包含特定字符的数据框中列表中的项目,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个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 ['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]
而且它的运行时间比我想要的要长得多。使用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
或者您可以使用
str.contains
from itertools import compress
import pandas as pd
df['Method'].apply(lambda x :list(compress(x,pd.Series(x).str.contains('::').tolist())))