Skip to content

Commit ca2a329

Browse files
committed
ENH: add data hashing routines
xref dask/dask#1807
1 parent 22d982a commit ca2a329

File tree

8 files changed

+538
-4
lines changed

8 files changed

+538
-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 data hash (:issue:`14729`)
25+
26+
1927
.. _whatsnew_0192.performance:
2028

2129
Performance Improvements

pandas/core/base.py

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -795,7 +795,78 @@ 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'):
802+
"""
803+
Return a data hash of the Series/DataFrame
804+
This is a 1-d array 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+
814+
Returns
815+
-------
816+
1d uint64 numpy array of hash values, same length as the
817+
object
818+
819+
Examples
820+
--------
821+
>>> pd.Index([1, 2, 3]).hash()
822+
array([ 6238072747940578789, 15839785061582574730,
823+
2185194620014831856], dtype=uint64)
824+
825+
>>> pd.Series([1, 2, 3]).hash()
826+
array([ 267474170112184751, 16863939785269199747,
827+
3948624847917518682], dtype=uint64)
828+
829+
>>> pd.Series([1, 2, 3]).hash(index=False)
830+
array([ 6238072747940578789, 15839785061582574730,
831+
2185194620014831856], dtype=uint64)
832+
833+
>>> pd.DataFrame({'A': [1, 2, 3]}).hash()
834+
array([ 267474170112184751, 16863939785269199747,
835+
3948624847917518682], dtype=uint64)
836+
837+
>>> pd.DataFrame({'A': [1, 2, 3], 'B': ['foo', 'bar', 'baz']}).hash()
838+
array([2236065623248835415, 5345384428795788641,
839+
46691607209239364], dtype=uint64)
840+
841+
Notes
842+
-----
843+
These functions do not hash attributes attached to the object
844+
e.g. name for Index/Series. Nor do they hash the columns of
845+
a DataFrame.
846+
847+
Mixed dtypes within a Series (or a column of a DataFrame) will
848+
be stringified, for example.
849+
850+
>>> Series(['1', 2, 3]).hash()
851+
array([ 8973981985592347666, 16940873351292606887,
852+
10100427194775696709], dtype=uint64)
853+
854+
>>> Series(['1', '2', '3']).hash()
855+
array([ 8973981985592347666, 16940873351292606887,
856+
10100427194775696709], dtype=uint64)
857+
858+
These have the same data hash, while a pure dtype is different.
859+
860+
>>> Series([1, 2, 3]).hash()
861+
array([ 267474170112184751, 16863939785269199747,
862+
3948624847917518682], dtype=uint64)
863+
864+
"""
865+
from pandas.tools.hashing import hash_pandas_object
866+
return hash_pandas_object(self, index=index, encoding=encoding)
867+
868+
869+
class IndexOpsMixin(HashableMixin):
799870
""" common ops mixin to support a unified inteface / docs for Series /
800871
Index
801872
"""

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

0 commit comments

Comments
 (0)