【发布时间】: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