首页 > 解决方案 > 扩展()不产生列表

问题描述

我正在使用字符串列表和包含字符串的数据框。想象一下场景:

A = ['the', 'a', 'with', 'from', 'on']
和一个数据框:
df = {'col1':['string', 'string'], 'col2':['镇上的人', '公交车上的人']}

我现在正在尝试在我的 data_frame 中创建一个新列,该列将在我的列表 A 中的 data_frame 的第 2 列中显示值(在这种情况下:the, from, a)

我写的是这样的:

def words_in_A(行):
     资源=[]
     对于 A 中的项目:
          如果在行中的项目:
              res.extend(项目)
              返回资源

df[col3] = df[col2].apply(lambda x: words_in_A(x))

我希望输出是一个包含多个值的列表:

列 1 列 2 列 3
将镇上的人串成“the”、“from”、“a”
把人串在公共汽车上 'the', 'on', 'a'

但是该函数只返回最后一项('a')而不是列表。我不确定为什么使用 extend() 没有为我生成列表。请帮忙!

标签: pythonpandas

解决方案


您的代码只需要一点缩进调整并使用append而不是extend. 如果您扩展,则该字符串'the'将被视为一个列表,并且每个字母都将附加到收集列表中。

def words_in_A(row): 
    lst = []
    for item in A:
        if item in row:
            lst.append(item) 
    return lst

老实说,虽然列表理解甚至 Shubham 的正则表达式答案都会比 快apply,但我坚持正确。这是您的数据框的时间安排,但有 20,000 行而不是 2 行。

with apply 0.078s
with list comp 0.076s
with regex 0.168s
with regex, no join 0.141s

和测试代码

from time import time

t0 = time()
df['col3'] = df['col2'].apply(words_in_A)
print('with apply', f'{time() - t0:.3f}s')

t0 = time()
df['col3'] = [[item for item in A if item in row] for row in df.col2]
print('with list comp', f'{time() - t0:.3f}s')

t0 = time()
pat = rf"(?i)\b(?:{'|'.join(A)})\b"
df['col3'] = df['col2'].str.findall(pat).str.join(', ')
print('with regex', f'{time() - t0:.3f}s')

t0 = time()
pat = rf"(?i)\b(?:{'|'.join(A)})\b"
df['col3'] = df['col2'].str.findall(pat)
print('with regex, no join', f'{time() - t0:.3f}s')

输出

         col1                 col2          col3
0      string  the man from a town  the, from, a
1      string    a person on a bus      a, on, a
2      string  the man from a town  the, from, a
3      string    a person on a bus      a, on, a
4      string  the man from a town  the, from, a
...       ...                  ...           ...
19995  string    a person on a bus      a, on, a
19996  string  the man from a town  the, from, a
19997  string    a person on a bus      a, on, a
19998  string  the man from a town  the, from, a
19999  string    a person on a bus      a, on, a

[20000 rows x 3 columns]

推荐阅读