仅保留包含特定字符的数据帧中列表中的项

2024-09-30 18:32:41 发布

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

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

跑起来比我想的要长得多。你知道吗


Tags: 方法nameindf列表forfoobar
2条回答

或者可以使用str.contains

 from itertools import compress
 import pandas as pd 

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

使用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

相关问题 更多 >