这是我的数据帧。
Student Studendid Student Studendid Student Studendid
0 Stud1 1 0 Stud1 ah274as 0 Stud1 1
1 Stud2 2 1 Stud2 ah474as 1 Stud2 2
2 Stud3 3 2 Stud3 ah454as 2 Stud3 3
3 Stud4 4 hash 3 Stud4 48sdfds hash 3 Stud4 4
4 Stud5 5 -> 4 Stud5 dash241 -> 4 Stud5 5
5 Stud6 6 5 Stud6 asda212 5 Stud6 6
6 Stud7 7 6 Stud7 askdkj2 6 Stud7 7
7 Stud8 8 7 Sud8 kadhh23 7 Stud8 8
8 Stud9 9 8 Stud9 asdhb27 8 Stud9 9
根据学生的情况,我想对学生ID进行散列。我已经尝试过hash()
函数。不幸的是,我还没有找到任何方法来恢复它。我想先散列,然后再散列。有什么方法可以散列Studend并将其散列回来?
df[Studendid] = df["Student"].hash()
Like@Ch3steR评论道:
这个正确的假设每个值都有一个唯一的";散列值";但是目前还不存在这样的散列函数。每个散列函数都容易发生冲突。
# Example for collision
hash(0.1) == hash(230584300921369408)
True
注意:根据Python 3.3,字符串和字节对象的值在哈希过程之前用随机值进行加盐处理。这意味着字符串的值将使用一个随机值进行修改,该值在每次解释器启动时都会发生变化这样做是为了避免dictionary hash attack
# Example taken martijn's answer: https://stackoverflow.com/a/27522708/12416453
>>> hash("235")
-310569535015251310
现在,打开一个新的会话。
>>> hash("235")
-1900164331622581997
但是,如果只有几行数据可以使用:
使用助手字典进行哈希,然后将key:values
映射回d1
字典并传递给Series.map
:
d2 = {hash(x):x for x in df['Student']}
d1 = {v:k for k, v in d2.items()}
df['Studendid']= df['Student'].map(d1)
df['orig']= df['Studendid'].map(d2)
print (df)
Student Studendid orig
0 Stud1 6001180169368329239 Stud1
1 Stud2 -1507322317280771023 Stud2
2 Stud3 -2262724814055039076 Stud3
3 Stud4 364063172999472918 Stud4
4 Stud5 8548751638627509914 Stud5
5 Stud6 5647607776109616031 Stud6
6 Stud7 729989721669472240 Stud7
7 Stud8 4828368150311261883 Stud8
8 Stud9 8466663427818502594 Stud9