pandas 如何在Python Dataframe(从固定宽度文件创建)上生成哈希或校验和值?

xyhw6mcr  于 2023-06-04  发布在  Python
关注(0)|答案(3)|浏览(177)

我有2个固定宽度的文件如下(唯一的变化是日期值开始位置14)。

sample_hash1.txt

GOKULKRISHNA 04/17/2018
ABCDEFGHIJKL 04/17/2018
111111111111 04/17/2018

sample_hash2.txt

GOKULKRISHNA 04/16/2018
ABCDEFGHIJKL 04/16/2018
111111111111 04/16/2018

使用pandas read_fwf,我正在阅读这个文件并创建一个Dataframe(通过排除日期值,只加载前13个字符)。我的数据框看起来像这样。

import pandas as pd
df1 = pd.read_fwf("sample_hash1.txt", colspecs=[(0,13)])
df2 = pd.read_fwf("sample_hash2.txt", colspecs=[(0,13)])

df1

GOKULKRISHNA
0  ABCDEFGHIJKL
1  111111111111

df2

GOKULKRISHNA
0  ABCDEFGHIJKL
1  111111111111

现在我尝试在每个dataframe上生成一个哈希值,但哈希值是不同的。我不知道这有什么问题。有没有人能把灯打开?我必须确定文件中的数据是否有任何更改(不包括日期列)。

print(hash(df1.values.tostring()))
-3571422965125408226

print(hash(df2.values.tostring()))
5039867957859242153

我正在将这些文件(每个文件大小约为2GB)加载到表中。每次我们从源接收完整文件时,有时数据没有变化(除了最后一列日期)。所以我的想法是拒绝这样的文件。因此,如果我可以在文件上生成散列并存储在某个地方(在表中),下次我可以将新文件散列值与存储的散列进行比较。所以我认为这是正确的方法。但坚持使用哈希生成。
我检查了这篇文章Most efficient property to hash for numpy array,但这不是我要找的

mgdq6dx1

mgdq6dx11#

现在可以使用pd.util.hash_pandas_object

hashlib.sha1(pd.util.hash_pandas_object(df).values).hexdigest()

对于一个有5000万行的 Dataframe ,这个方法花了我10秒,而to_json()方法花了一分钟多。

bqujaahr

bqujaahr2#

使用字符串表示 Dataframe 。

import hashlib

print(hashlib.sha256(df1.to_json().encode()).hexdigest())
print(hashlib.sha256(df2.to_json().encode()).hexdigest())

print(hashlib.sha256(df1.to_csv().encode()).hexdigest())
print(hashlib.sha256(df2.to_csv().encode()).hexdigest())
q9yhzks0

q9yhzks03#

这里的其他答案确实忘记了 Dataframe 的列名(列索引)。pd.util.hash_pandas_object()为 Dataframe 的每一行创建一系列哈希值,包括它的索引(行名称)。但是列的名称并不重要,正如您在这里看到的:

>>> from pandas import *
>>> from pandas import util
>>> util.hash_pandas_object(DataFrame({'A': [1,2,3], 'B': [4,5,6]}))
0     580038878669277522
1    2529894495349307502
2    4389717532997776129
dtype: uint64
>>> util.hash_pandas_object(DataFrame({'Foo': [1,2,3], 'Bar': [4,5,6]}))
0     580038878669277522
1    2529894495349307502
2    4389717532997776129
dtype: uint64

我的解决方案

df = DataFrame({'A': [1,2,3], 'B': [4,5,6]})

hash = pandas.util.hash_pandas_object(df)

# append hash of the columns
hash = pandas.concat(
    [hash, pandas.util.hash_pandas_object(df.columns)]
)

# hash the series of hashes
hash = hashlib.sha1(hash.values).hexdigest()

print(hash)

相关问题