【问题标题】:Fastest one for apply function to update whole rows of specific column in Python最快的应用函数来更新 Python 中特定列的整行
【发布时间】:2021-06-27 10:25:38
【问题描述】:

我有一些大型 DataFrame(x 百万行)。
我必须将特定列值(整行)更新为散列值。 我想知道最简单快捷的方法。

这是一个示例代码。

import pandas as pd 
import numpy as np
import hashlib

def hash(value: str) -> str: 
    result = hashlib.pbkdf2_hmac(
        "sha256",
        value.encode("utf-8"),
        salt="sample".encode("utf-8"),
        iterations=100,
    )

    return result.hex()

n = 100000

df = pd.DataFrame({
        "col1": np.random.normal(size=n),
        "col2": np.random.normal(size=n),
        "col3": np.random.normal(size=n),
    }
    , dtype=str)

# target columns
columns = ["col1", "col3"]

# what I've tested
%timeit df[columns].applymap(hash)
%timeit for c in columns: df[c].apply(hash)
%timeit np.frompyfunc(hash, 1, 1)(df[columns].to_numpy())

# Note: Finally, I have to do something like this
# df[columns] = df[columns].applymap(hash)
# df.to_csv("sample.csv")

示例代码中的三个示例性能几乎相同。
我知道矢量化对 python 很重要。 但我不知道我是如何使它矢量化的..

谁能帮我找到答案?

【问题讨论】:

  • 看起来您的问题不需要矢量化,因为在计算散列值时每个元素彼此独立。但是,您可以使用 dask 的 applymap 在 df 上并行化您的函数。
  • @Scratch'N'Purr 感谢您的评论!我知道这不是矢量化的问题。我试过dask的applymap。然后我在我的环境中更快地得到它。附言我必须在 Azure Functions 上执行它,但它在那里可以正常运行。 (我知道这种繁重的过程不适合Functions..)

标签: python pandas dataframe performance


【解决方案1】:

我添加了一个使用 dask 的 applymap 的。谢谢你,Scratch'N'Purr。
它运行良好(在我的机器上要快 x2.74)。

import pandas as pd 
import numpy as np
import hashlib
import dask.dataframe as dd
import multiprocessing

def hash(value: str) -> str: 
    result = hashlib.pbkdf2_hmac(
        "sha256",
        value.encode("utf-8"),
        salt="sample".encode("utf-8"),
        iterations=100,
    )

    return result.hex()

n = 100000

df = pd.DataFrame({
    "col1": np.random.normal(size=n),
    "col2": np.random.normal(size=n),
    "col3": np.random.normal(size=n),
    }
    , dtype=str)


# target columns
columns = ["col1", "col3"]

# what I've tested
%timeit -r 1 df[columns].applymap(hash)
%timeit for c in columns: df[c].apply(hash)
%timeit np.frompyfunc(hash, 1, 1)(df[columns].to_numpy())

# added one
ddf = dd.from_pandas(df, npartitions=multiprocessing.cpu_count())
%timeit -r 1 ddf[columns].applymap(hash).compute()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多