python - 将多次返回的向量化函数应用于 pandas 数据帧

标签 python pandas dataframe

我有一个数据框,其中包含一个包含“Log”字符串的列。 我想根据从“日志”列解析的值创建一个新列。 目前,我正在使用 .apply() 和以下函数:

def classification(row):
    if 'A' in row['Log']:
        return 'Situation A'
    elif 'B' in row['Log']:
        return 'Situation B'
    elif 'C' in row['Log']:
        return 'Situation C'
    return 'Check'

它看起来像: df['分类'] = df.apply(classification, axis=1) 问题是它需要很多时间(对于具有 4M 行的数据帧大约需要 3 分钟),我正在寻找一种更快的方法。 我看到一些用户使用运行速度更快的矢量化函数的示例,但这些函数中没有 if 语句。 我的问题 - 是否可以对我添加的函数进行矢量化以及最快的执行方式是什么
这个任务?

最佳答案

我不确定使用嵌套的 numpy.where 是否会提高性能:这里有一些 4M 行的测试性能

import numpy as np
import pandas as pd

ls = ['Abc', 'Bert', 'Colv', 'Dia']
df =  pd.DataFrame({'Log': np.random.choice(ls, 4_000_000)})

df['Log_where'] = np.where(df['Log'].str.contains('A'), 'Situation A', 
                      np.where(df['Log'].str.contains('B'), 'Situation B', 
                          np.where(df['Log'].str.contains('C'), 'Situation C', 'check')))


def classification(x):
    if 'A' in x:
        return 'Situation A'
    elif 'B' in x:
        return 'Situation B'
    elif 'C' in x:
        return 'Situation C'
    return 'Check'


df['Log_apply'] = df['Log'].apply(classification)

嵌套 np.where 性能

 %timeit np.where(df['Log'].str.contains('A'), 'Situation A', np.where(df['Log'].str.contains('B'), 'Situation B',np.where(df['Log'].str.contains('C'), 'Situation C', 'check')))
8.59 s ± 1.71 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

应用 map 性能

%timeit df['Log'].apply(classification)
911 ms ± 146 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

至少在我的机器上使用嵌套的 np.where 几乎比 applymap 慢 10 倍。

最后一句话:使用评论中建议的解决方案,即:

d = {'A': 'Situation A',
     'B': 'Situation B',
     'C': 'Situation C'}
df['Log_extract'] = df['Log'].str.extract('(A|B|C)')
df['Log_extract'] = df['Log_extract'].map(d).fillna('Check')

存在以下问题:

  1. 不会一定会更快 - 在我的机器上测试:

    %timeit df['Log_extract'] = df['Log'].str.extract('(A|B|C)')
    3.74 s ± 70.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
  2. .extract 方法遵循字符串顺序,即从字符串 'AB' 中提取 'A' 并从 >'BA' 将提取'B'。另一方面,OP 函数classification 具有提取的分层顺序,因此在两种情况下都提取'A'

关于python - 将多次返回的向量化函数应用于 pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59722277/

相关文章:

python - 使用 Python/Selenium 选择单选按钮

python - 从 pyaudio-stream 获取音频样本作为 float

Python 将 GCS 中的 .json 文件并行读取到 pandas DF 中

python - 选择一列来制作直方图

python - Pandas 计算具有列表而不是单个值的列的平均值

python - 将多列合并为一列 pandas

python - 在Python中的某个单词后打印

python - pandas - 从具有多个值的列中删除重复项,计算项目

python - 以 html 电子邮件的形式发送 pandas dataframe 数据

dataframe - 派斯帕克 : Subtracting/Difference pyspark dataframes based on all columns