python - 将行移动到另一个数据帧时如何加快 Pandas contains 的速度

标签 python pandas dataframe

我有一个小脚本,用于检查条件,如果为 true,则将 pandas 数据帧行移动到新数据帧,然后从原始数据帧中删除该行。

最初,我是用这个正则表达式做的,但这很慢,在阅读了一些之后,我尝试了这种方式 - 它稍微快一点。

我使用的生产数据在数百万行中运行,因此节省的任何时间都会有很大帮助。

我可以做些什么来进一步优化它吗?

import pandas as pd


data = [['thomas cook', 222], ['holidays', 333], ['cheap flights', 444], ['thomascook holidays', 555]]
df1 = pd.DataFrame(data, columns=['query', 'clicks'])
df2 = pd.DataFrame(columns=df1.columns)

print(df1)
                 query  clicks
0          thomas cook     222
1             holidays     333
2        cheap flights     444
3  thomascook holidays     555

brand_terms = ['thomas cook', 'thomascook', 'thomas-cook']
for brand_term in brand_terms:
    condtion = df1[df1["query"].str.contains(brand_term, case=False, regex=False)]
    df2 = df2.append(condtion, ignore_index=True)
    df1.drop(condtion.index, inplace=True)

print(df1)
           query  clicks
1       holidays     333
2  cheap flights     444


print(df2)
                 query clicks
0          thomas cook    222
1  thomascook holidays    555

最佳答案

您可以使用str.contains()并且不要更改regex参数:

df2=(df1.loc[df1["query"].str.contains(pat='|'.join(brand_terms), case=False)]
        .reset_index(drop=True))

df2 的输出:

    query                   clicks
0   thomas cook             222
1   thomascook holidays     555

更新:

您可以使用~(按位否定运算符)(例如):

df1=(df1.loc[~df1["query"].str.contains(pat='|'.join(brand_terms), case=False)])
        .reset_index(drop=True)

注意:

为了简单和提高性能,将您的条件存储在变量中:

m=df1["query"].str.contains(pat='|'.join(brand_terms), case=False)
df1=df1.loc[~m].reset_index(drop=True)
df2=df1.loc[m].reset_index(drop=True)

关于python - 将行移动到另一个数据帧时如何加快 Pandas contains 的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68781074/

相关文章:

python - 将 DataFrame 转换为对象数组

python-3.x - 如何使用python提取excel表中的不同表格

python - 如何替换数据框列中大于特定值的值?

python - pandas read_csv 将所有值放在一列和一行中

python pandas 溢出错误数据帧

python - 如果另一列包含字符串,则替换 pandas 中的一列

Python 属性 getter 和 setter 装饰器不可调用

python - 计算三种方法的欧氏距离

python - 如何在 Python 中执行此 Ruby if-with-and 并且不会使列表索引超出范围

python - SVN/python库