获取原始数据 --> 转换并与其他文件连接 --> 通过电子邮件发送给最终用户进行审核
什么是最佳方法?
'employee_id'+'customer_id'+'timestamp'
很长,并且您对不太可能发生冲突的内容感兴趣,可以用哈希替换它。哈希的范围和质量将确定碰撞的概率。也许最简单的方法是使用内置hash
。假设您的DataFrame是df
,并且列是字符串,那么就是:(df.employee_id + df.customer_id + df.timestamp).apply(hash)
编辑
在此问题的回答的基础上,您可以像这样构建10个字符的哈希值:
import hashlib
df['survey_id'] = (df.employee_id + df.customer_id + df.timestamp).apply(
lambda s: hashlib.md5(s).digest().encode('base64')[: 10])
我曾经遇到过类似的问题,我是这样解决的:
import hashlib
import pandas as pd
df = pd.DataFrame.from_dict({'mine': ['yours', 'amazing', 'pajamas'], 'have': ['something', 'nothing', 'between'], 'num': [1, 2, 3]})
hashes = []
for index, row in df.iterrows():
hashes.append(hashlib.md5(str(row).encode('utf-8')).hexdigest())
# if you want the hashes in the df,
# in my case, I needed them to form a JSON entry per row
df['hash'] = hashes
结果将形成一个md5哈希值,但你实际上可以使用任何你需要的哈希函数。
如果有人正在寻找模块化的函数,请将其保存到文件中以在需要时使用。(适用于Pandas DataFrames)
df
是您的数据框,columns
是一个要进行哈希操作的列列表,name
是具有哈希值的新列的名称。
返回原始数据框的副本,其中包含每行哈希值的新列。
def hash_cols(df, columns, name="hash"):
new_df = df.copy()
def func(row, cols):
col_data = []
for col in cols:
col_data.append(str(row.at[col]))
col_combined = ''.join(col_data).encode()
hashed_col = sha256(col_combined).hexdigest()
return hashed_col
new_df[name] = new_df.apply(lambda row: func(row,columns), axis=1)
return new_df