Skip to content

Commit 7605b68

Browse files
committed
ENH: add data hashing routines
xref dask/dask#1807
1 parent b1d9599 commit 7605b68

File tree

8 files changed

+590
-4
lines changed

8 files changed

+590
-4
lines changed

asv_bench/benchmarks/algorithms.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import numpy as np
22
import pandas as pd
3+
from pandas.util import testing as tm
34

45

56
class algorithm(object):
@@ -55,3 +56,35 @@ def time_add_overflow_neg_arr(self):
5556

5657
def time_add_overflow_mixed_arr(self):
5758
self.checked_add(self.arr, self.arrmixed)
59+
60+
61+
class hashing(object):
62+
goal_time = 0.2
63+
64+
def setup(self):
65+
N = 100000
66+
67+
self.df = pd.DataFrame(
68+
{'A': pd.Series(tm.makeStringIndex(100).take(
69+
np.random.randint(0, 100, size=N))),
70+
'B': pd.Series(tm.makeStringIndex(10000).take(
71+
np.random.randint(0, 10000, size=N))),
72+
'D': np.random.randn(N),
73+
'E': np.arange(N),
74+
'F': pd.date_range('20110101', freq='s', periods=N),
75+
'G': pd.timedelta_range('1 day', freq='s', periods=N),
76+
})
77+
self.df['C'] = self.df['B'].astype('category')
78+
self.df.iloc[10:20] = np.nan
79+
80+
def time_frame(self):
81+
self.df.hash()
82+
83+
def time_series_int(self):
84+
self.df.E.hash()
85+
86+
def time_series_string(self):
87+
self.df.B.hash()
88+
89+
def time_series_categorical(self):
90+
self.df.C.hash()

doc/source/whatsnew/v0.19.2.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@ Highlights include:
1616
:backlinks: none
1717

1818

19+
.. _whatsnew_0192.enhancements:
20+
21+
Enhancements
22+
~~~~~~~~~~~~
23+
24+
- ``Series/DataFrame/Index`` gain a ``.hash()`` method to provide a row-wise unique data hash , see :meth:`pandas.DataFrame.hash` (:issue:`14729`)
25+
26+
1927
.. _whatsnew_0192.performance:
2028

2129
Performance Improvements

pandas/core/base.py

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -795,7 +795,99 @@ def __unicode__(self):
795795
return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype)
796796

797797

798-
class IndexOpsMixin(object):
798+
class HashableMixin(object):
799+
""" provide methods for hashable pandas objects """
800+
801+
def hash(self, index=True, encoding='utf8', hash_key=None):
802+
"""
803+
Return a data hash of the Index/Series/DataFrame
804+
This is a 1-d Series of unique hashses of all of the elements in that
805+
row, including the index if desired.
806+
807+
Parameters
808+
----------
809+
index : boolean, default True
810+
include the index in the hash (if Series/DataFrame)
811+
encoding : string, default 'utf8'
812+
encoding for data & key when strings
813+
hash_key : string, must be 16 bytes length if passed
814+
815+
Returns
816+
-------
817+
Series of uint64 hash values. The index of the Series
818+
will be the original index (Series/DataFrame),
819+
or the original object if Index
820+
821+
Examples
822+
--------
823+
>>> pd.Index([1, 2, 3]).hash()
824+
1 6238072747940578789
825+
2 15839785061582574730
826+
3 2185194620014831856
827+
dtype: uint64
828+
829+
>>> pd.Series([1, 2, 3], index=[2, 3, 4]).hash()
830+
2 16107259231694759481
831+
3 12811061657343452814
832+
4 1341665827200607204
833+
dtype: uint64
834+
835+
>>> pd.Series([1, 2, 3]).hash(index=False)
836+
0 6238072747940578789
837+
1 15839785061582574730
838+
2 2185194620014831856
839+
dtype: uint64
840+
841+
>>> pd.DataFrame({'A': [1, 2, 3]}).hash()
842+
0 267474170112184751
843+
1 16863939785269199747
844+
2 3948624847917518682
845+
dtype: uint64
846+
847+
>>> pd.DataFrame({'A': [1, 2, 3], 'B': ['foo', 'bar', 'baz']}).hash()
848+
0 11603696091789712533
849+
1 5345384428795788641
850+
2 46691607209239364
851+
dtype: uint64
852+
853+
In [10]: pd.DataFrame({'A': [1, 1, 2], 'B': ['foo', 'bar', 'foo'],
854+
'C': [1, 2, 3]}).set_index(['A', 'B']).hash()
855+
A B
856+
1 foo 553964757138028680
857+
bar 13757638258637221887
858+
2 foo 4843577173406411690
859+
dtype: uint64
860+
861+
Notes
862+
-----
863+
These functions do not hash attributes attached to the object
864+
e.g. name for Index/Series. Nor do they hash the columns of
865+
a DataFrame.
866+
867+
Mixed dtypes within a Series (or a column of a DataFrame) will
868+
be stringified, for example.
869+
870+
>>> Series(['1', 2, 3]).hash()
871+
array([ 8973981985592347666, 16940873351292606887,
872+
10100427194775696709], dtype=uint64)
873+
874+
>>> Series(['1', '2', '3']).hash()
875+
array([ 8973981985592347666, 16940873351292606887,
876+
10100427194775696709], dtype=uint64)
877+
878+
These have the same data hash, while a pure dtype is different.
879+
880+
>>> Series([1, 2, 3]).hash()
881+
array([ 267474170112184751, 16863939785269199747,
882+
3948624847917518682], dtype=uint64)
883+
884+
"""
885+
from pandas.tools.hashing import hash_pandas_object
886+
return hash_pandas_object(self, index=index, encoding=encoding,
887+
hash_key=hash_key)
888+
889+
890+
class IndexOpsMixin(HashableMixin):
799891
""" common ops mixin to support a unified inteface / docs for Series /
800892
Index
801893
"""

pandas/core/frame.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@
201201
# DataFrame class
202202

203203

204-
class DataFrame(NDFrame):
204+
class DataFrame(NDFrame, base.HashableMixin):
205205
""" Two-dimensional size-mutable, potentially heterogeneous tabular data
206206
structure with labeled axes (rows and columns). Arithmetic operations
207207
align on both row and column labels. Can be thought of as a dict-like

pandas/src/hash.pyx

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# cython: profile=False
2+
# Translated from the reference implementation
3+
# at https://github.com/veorq/SipHash
4+
5+
import cython
6+
cimport numpy as cnp
7+
import numpy as np
8+
from numpy cimport ndarray, uint8_t, uint32_t, uint64_t
9+
10+
from cpython cimport (PyString_Check,
11+
PyBytes_Check,
12+
PyUnicode_Check)
13+
from libc.stdlib cimport malloc, free
14+
15+
DEF cROUNDS = 2
16+
DEF dROUNDS = 4
17+
18+
19+
@cython.boundscheck(False)
20+
def hash_object_array(ndarray[object] arr, object key, object encoding='utf8'):
21+
"""
22+
Parameters
23+
----------
24+
arr : 1-d object ndarray of objects
25+
key : hash key, must be 16 byte len encoded
26+
encoding : encoding for key & arr, default to 'utf8'
27+
28+
Returns
29+
-------
30+
1-d uint64 ndarray of hashes
31+
32+
"""
33+
cdef:
34+
Py_ssize_t i, l, n
35+
ndarray[uint64_t] result
36+
bytes data, k
37+
uint8_t *kb, *lens
38+
char **vecs, *cdata
39+
object val
40+
41+
k = <bytes>key.encode(encoding)
42+
kb = <uint8_t *>k
43+
if len(k) != 16:
44+
raise ValueError(
45+
'key should be a 16-byte string encoded, got {!r} (len {})'.format(
46+
k, len(k)))
47+
48+
n = len(arr)
49+
50+
# create an array of bytes
51+
vecs = <char **> malloc(n * sizeof(char *))
52+
lens = <uint8_t*> malloc(n * sizeof(uint8_t))
53+
54+
cdef list datas = []
55+
for i in range(n):
56+
val = arr[i]
57+
if PyString_Check(val):
58+
data = <bytes>val.encode(encoding)
59+
elif PyBytes_Check(val):
60+
data = <bytes>val
61+
elif PyUnicode_Check(val):
62+
data = <bytes>val.encode(encoding)
63+
else:
64+
# non-strings
65+
data = <bytes>str(val).encode(encoding)
66+
67+
l = len(data)
68+
lens[i] = l
69+
cdata = data
70+
71+
# keep the refernce alive thru the end of the
72+
# function
73+
datas.append(data)
74+
vecs[i] = cdata
75+
76+
result = np.empty(n, dtype=np.uint64)
77+
with nogil:
78+
for i in range(n):
79+
result[i] = low_level_siphash(<uint8_t *>vecs[i], lens[i], kb)
80+
81+
free(vecs)
82+
free(lens)
83+
return result
84+
85+
cdef inline uint64_t _rotl(uint64_t x, uint64_t b) nogil:
86+
return (x << b) | (x >> (64 - b))
87+
88+
cdef inline void u32to8_le(uint8_t* p, uint32_t v) nogil:
89+
p[0] = <uint8_t>(v)
90+
p[1] = <uint8_t>(v >> 8)
91+
p[2] = <uint8_t>(v >> 16)
92+
p[3] = <uint8_t>(v >> 24)
93+
94+
cdef inline void u64to8_le(uint8_t* p, uint64_t v) nogil:
95+
u32to8_le(p, <uint32_t>v)
96+
u32to8_le(p + 4, <uint32_t>(v >> 32))
97+
98+
cdef inline uint64_t u8to64_le(uint8_t* p) nogil:
99+
return (<uint64_t>p[0] |
100+
<uint64_t>p[1] << 8 |
101+
<uint64_t>p[2] << 16 |
102+
<uint64_t>p[3] << 24 |
103+
<uint64_t>p[4] << 32 |
104+
<uint64_t>p[5] << 40 |
105+
<uint64_t>p[6] << 48 |
106+
<uint64_t>p[7] << 56)
107+
108+
cdef inline void _sipround(uint64_t* v0, uint64_t* v1,
109+
uint64_t* v2, uint64_t* v3) nogil:
110+
v0[0] += v1[0]
111+
v1[0] = _rotl(v1[0], 13)
112+
v1[0] ^= v0[0]
113+
v0[0] = _rotl(v0[0], 32)
114+
v2[0] += v3[0]
115+
v3[0] = _rotl(v3[0], 16)
116+
v3[0] ^= v2[0]
117+
v0[0] += v3[0]
118+
v3[0] = _rotl(v3[0], 21)
119+
v3[0] ^= v0[0]
120+
v2[0] += v1[0]
121+
v1[0] = _rotl(v1[0], 17)
122+
v1[0] ^= v2[0]
123+
v2[0] = _rotl(v2[0], 32)
124+
125+
cpdef uint64_t siphash(bytes data, bytes key) except? 0:
126+
if len(key) != 16:
127+
raise ValueError(
128+
'key should be a 16-byte bytestring, got {!r} (len {})'.format(
129+
key, len(key)))
130+
return low_level_siphash(data, len(data), key)
131+
132+
133+
@cython.cdivision(True)
134+
cdef uint64_t low_level_siphash(uint8_t* data, size_t datalen,
135+
uint8_t* key) nogil:
136+
cdef uint64_t v0 = 0x736f6d6570736575ULL
137+
cdef uint64_t v1 = 0x646f72616e646f6dULL
138+
cdef uint64_t v2 = 0x6c7967656e657261ULL
139+
cdef uint64_t v3 = 0x7465646279746573ULL
140+
cdef uint64_t b
141+
cdef uint64_t k0 = u8to64_le(key)
142+
cdef uint64_t k1 = u8to64_le(key + 8)
143+
cdef uint64_t m
144+
cdef int i
145+
cdef uint8_t* end = data + datalen - (datalen % sizeof(uint64_t))
146+
cdef int left = datalen & 7
147+
cdef int left_byte
148+
149+
b = (<uint64_t>datalen) << 56
150+
v3 ^= k1
151+
v2 ^= k0
152+
v1 ^= k1
153+
v0 ^= k0
154+
155+
while (data != end):
156+
m = u8to64_le(data)
157+
v3 ^= m
158+
for i in range(cROUNDS):
159+
_sipround(&v0, &v1, &v2, &v3)
160+
v0 ^= m
161+
162+
data += sizeof(uint64_t)
163+
164+
for i in range(left-1, -1, -1):
165+
b |= (<uint64_t>data[i]) << (i * 8)
166+
167+
v3 ^= b
168+
169+
for i in range(cROUNDS):
170+
_sipround(&v0, &v1, &v2, &v3)
171+
172+
v0 ^= b
173+
v2 ^= 0xff
174+
175+
for i in range(dROUNDS):
176+
_sipround(&v0, &v1, &v2, &v3)
177+
178+
b = v0 ^ v1 ^ v2 ^ v3
179+
180+
return b

0 commit comments

Comments
 (0)