将一个新列添加到数据帧中,该数据帧包含选定的几个列的散列



我正在努力找出实现这一点的最佳方法——我们希望每行创建一个列的哈希,并将该哈希添加为新列。所以每一行都有自己的散列。我曾考虑使用dataframe.apply,但不确定如何正确格式化调用,也没有看到我在文档中描述的好例子。

原始数据帧:

user_id     user_jumps  d_steps
1015       48          0
1015       23        -25
1015       79         56
2023       10          0
2023       20         10

输出数据帧:

user_id     steps    d_steps   hash
1015       48          0    hash(user_id+Steps+d_steps)
1015       23        -25    hash(user_id+Steps+d_steps)
1015       79         56    hash(user_id+Steps+d_steps)
2023       10          0    hash(user_id+Steps+d_steps)
2023       20         10    hash(user_id+Steps+d_steps)

您需要在每行上使用一个应用函数:

import pandas as pd
df = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f']], columns=['user_id', 'steps', 'd_steps'])
print(
df.apply(lambda x: hash(x['user_id'] + x['steps'] + x['d_steps']), axis=1)
)

这意味着:对于df的每一行,采用user_id、steps和d_steps的串联并应用散列。

取决于你想要什么样的散列,但我只需要遍历列并计算总和的散列(作为编码字符串(,如下所示:

`

# import your stuff
import pandas as pd
import haslib
# create a sample dataframe
d = {'user_id': [1, 2], 'user_jumps': [3, 4], 'd_steps':[5,6]}
df=pd.DataFrame(data=d)
# create a column of the sum of the first two columns
df['hash']=df['user_id']+df['user_jumps']+df['d_steps']
temp_list=[]
# iterate through the new column you created,
# and append its hash to a temp list for now
for val in df['hash'].values.tolist():
m = hashlib.sha256()
print(val)
# encode first
m.update(str(val).encode("UTF-8"))
# then append the result to the list
temp_list.append(m.digest())
# append the list you created back to that column
df['hash']=temp_list

`

最新更新