Skip to content

Commit 23e4257

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

File tree

8 files changed

+452
-4
lines changed

8 files changed

+452
-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: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -795,7 +795,53 @@ 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):
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+
812+
Returns
813+
-------
814+
1d uint64 numpy array of hash values, same length as the
815+
object
816+
817+
Examples
818+
--------
819+
>>> pd.Index([1, 2, 3]).hash()
820+
array([ 6238072747940578789, 15839785061582574730,
821+
2185194620014831856], dtype=uint64)
822+
823+
>>> pd.Series([1, 2, 3]).hash()
824+
array([ 267474170112184751, 16863939785269199747,
825+
3948624847917518682], dtype=uint64)
826+
827+
>>> pd.Series([1, 2, 3]).hash(index=False)
828+
array([ 6238072747940578789, 15839785061582574730,
829+
2185194620014831856], dtype=uint64)
830+
831+
>>> pd.DataFrame({'A': [1, 2, 3]}).hash()
832+
array([ 267474170112184751, 16863939785269199747,
833+
3948624847917518682], dtype=uint64)
834+
835+
>>> pd.DataFrame({'A': [1, 2, 3], 'B': ['foo', 'bar', 'baz']}).hash()
836+
array([2236065623248835415, 5345384428795788641,
837+
46691607209239364], dtype=uint64)
838+
839+
"""
840+
from pandas.tools.hashing import hash_pandas_object
841+
return hash_pandas_object(self, index=index)
842+
843+
844+
class IndexOpsMixin(HashableMixin):
799845
""" common ops mixin to support a unified inteface / docs for Series /
800846
Index
801847
"""

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

0 commit comments

Comments
 (0)