gpt4 book ai didi

python - 每次为 Pandas DataFrame 获取相同的哈希值

转载 作者:IT老高 更新时间:2023-10-28 20:54:29 28 4
gpt4 key购买 nike

我的目标是获取 DataFrame 的唯一哈希值。我从 .csv 文件中获取它。重点是每次我调用 hash() 时都得到相同的哈希值。

我的想法是创建函数

def _get_array_hash(arr):
arr_hashable = arr.values
arr_hashable.flags.writeable = False
hash_ = hash(arr_hashable.data)
return hash_

调用底层 numpy 数组,将其设置为不可变状态并获取缓冲区的哈希值。

内联更新。

自 08.11.2016 起,此版本的功能不再起作用。相反,您应该使用

hash(df.values.tobytes())

查看 Most efficient property to hash for numpy array 的评论.

内联 UPD 结束。

它适用于常规 pandas 数组:

In [12]: data = pd.DataFrame({'A': [0], 'B': [1]})

In [13]: _get_array_hash(data)
Out[13]: -5522125492475424165

In [14]: _get_array_hash(data)
Out[14]: -5522125492475424165

然后我尝试将其应用于从 .csv 文件中获得的 DataFrame:

In [15]: fpath = 'foo/bar.csv'

In [16]: data_from_file = pd.read_csv(fpath)

In [17]: _get_array_hash(data_from_file)
Out[17]: 6997017925422497085

In [18]: _get_array_hash(data_from_file)
Out[18]: -7524466731745902730

谁能解释一下,这怎么可能?

我可以用它创建新的DataFrame,比如

new_data = pd.DataFrame(data=data_from_file.values, 
columns=data_from_file.columns,
index=data_from_file.index)

它又可以工作了

In [25]: _get_array_hash(new_data)
Out[25]: -3546154109803008241

In [26]: _get_array_hash(new_data)
Out[26]: -3546154109803008241

但我的目标是在应用程序启动时为数据帧保留相同的哈希值,以便从缓存中检索一些值。

最佳答案

从 Pandas 0.20.1 开始,您可以使用鲜为人知(且文档记录不充分)的 hash_pandas_object (source code),它最近是 made public。在 pandas.util 中。它为数据帧的到达行返回一个哈希值(也适用于系列等)

import pandas as pd
import numpy as np

np.random.seed(42)
arr = np.random.choice(['foo', 'bar', 42], size=(3,4))
df = pd.DataFrame(arr)

print(df)
# 0 1 2 3
# 0 42 foo 42 42
# 1 foo foo 42 bar
# 2 42 42 42 42

from pandas.util import hash_pandas_object
h = hash_pandas_object(df)

print(h)
# 0 5559921529589760079
# 1 16825627446701693880
# 2 7171023939017372657
# dtype: uint64

如果您想要所有行的整体哈希,您可以随时使用 hash_pandas_object(df).sum()

关于python - 每次为 Pandas DataFrame 获取相同的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31567401/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com