使用哈希值转换dataframe列

2024-09-28 21:10:55 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据帧

  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()

Tags: 方法dfhashstudent学生stud1stud4stud2
1条回答
网友
1楼 · 发布于 2024-09-28 21:10:55

就像@Ch3steR评论的那样:

This correct assuming every value has a unique "hash value" but there doesn't exist such hash function as of now. Every hash function is collision prone.

# Example for collision
hash(0.1) == hash(230584300921369408)
True

注意在Python 3.3中,字符串和字节对象的值在散列处理之前用随机值进行标记。这意味着字符串的值将被修改为一个随机值,该值在每次解释器启动时都会更改这样做是为了避免^{}

# Example taken martijn's answer: https://stackoverflow.com/a/27522708/12416453
>>> hash("235")
-310569535015251310

现在,打开一个新会话

>>> hash("235")
-1900164331622581997

但如果您只能使用几行数据:

使用helper dictionary进行散列,然后将swapkey:values映射回d1dictionary并传递到^{}

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

相关问题 更多 >