使用python pandas在数据框中的选定列为数据的每一行创建哈希值 [英] Create hash value for each row of data with selected columns in dataframe in python pandas
本文介绍了使用python pandas在数据框中的选定列为数据的每一行创建哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我问了类似的问题中有关为数据的每一行创建哈希值的信息.我知道我可以使用hashlib.md5(b'Hello World').hexdigest()
之类的东西来对字符串进行哈希处理,但是数据框中的行又如何呢?
I have asked similar question in R about creating hash value for each row of data. I know that I can use something like hashlib.md5(b'Hello World').hexdigest()
to hash a string, but how about a row in a dataframe?
我起草了如下代码:
for index, row in course_staff_df.iterrows():
temp_df.loc[index,'hash'] = hashlib.md5(str(row[['cola','colb']].values)).hexdigest()
对我来说似乎不是很pythonic,有什么更好的解决方法吗?
It seems not very pythonic to me, any better solution?
推荐答案
或者简单地:
df.apply(lambda x: hash(tuple(x)), axis = 1)
例如:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(3,5))
print df
df.apply(lambda x: hash(tuple(x)), axis = 1)
0 1 2 3 4
0 0.728046 0.542013 0.672425 0.374253 0.718211
1 0.875581 0.512513 0.826147 0.748880 0.835621
2 0.451142 0.178005 0.002384 0.060760 0.098650
0 5024405147753823273
1 -798936807792898628
2 -8745618293760919309
这篇关于使用python pandas在数据框中的选定列为数据的每一行创建哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文