繁体   English   中英

将具有多个返回值的矢量化函数应用到 Pandas 数据帧

[英]Applying a vectorized function with several returns to pandas dataframe

我有一个数据框,其中包含一个包含“日志”字符串的列。 我想根据我从“日志”列解析的值创建一个新列。 目前,我将.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['Classification'] = df.apply(classification, axis=1)问题是它需要很多时间(大约 3 分钟到具有 4M 行的数据框),我正在寻找一种更快的方法. 我看到一些用户使用矢量化函数的例子,这些函数运行得更快,但函数中没有 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)

应用地图性能

%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. 不会necessarely更快-测试我的机器上:

     %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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM