[英]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')
有以下問題:
它不會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)
.extract
方法遵循字符串順序,即從字符串'AB'
提取'A'
,從'BA'
提取'B'
。 另一方面,OP 函數classification
具有提取的分層順序,因此在兩種情況下都提取'A'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.