Python 将新列添加到数据帧中,该数据帧包含选定的几列组合的哈希值
我正在努力找出实现这一点的最佳方法,我们希望为每行创建一个列哈希,并将该哈希添加为一个新列。所以每一行都有自己的散列。我曾考虑使用dataframe.apply,但不确定如何正确设置调用的格式,也没有看到我在文档中描述的好例子 原始数据帧:Python 将新列添加到数据帧中,该数据帧包含选定的几列组合的哈希值,python,dataframe,Python,Dataframe,我正在努力找出实现这一点的最佳方法,我们希望为每行创建一个列哈希,并将该哈希添加为一个新列。所以每一行都有自己的散列。我曾考虑使用dataframe.apply,但不确定如何正确设置调用的格式,也没有看到我在文档中描述的好例子 原始数据帧: user_id user_jumps d_steps 1015 48 0 1015 23 -25 1015 79 56 2023
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的串联并应用散列 取决于您想要什么类型的散列,但我只需遍历该列并计算总和的散列(作为编码字符串),如下所示: `
`df['hash']=hash((df['user\u id'],df['steps'],df['d\u steps'])能解决这个问题吗?(你的第二个数据帧是不同的列,但数据相同,如果需要,只需重命名?)我会将散列的输出输入到一个新列中。因此,第四列将被添加到数据框中,然后应用函数用于填写数据。Savior谢谢。刚刚拿起python开始工作,还在学习。没问题。寻找一些Pandas应用的示例,有时它有点不直观,但非常有用。这不是数据帧的反模式吗?
# 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