【发布时间】:2021-08-17 01:00:35
【问题描述】:
获取原始数据 --> 对其进行转换并将其与其他文件合并 --> 通过电子邮件发送给最终用户进行审查
最好的方法是什么?
【问题讨论】:
获取原始数据 --> 对其进行转换并将其与其他文件合并 --> 通过电子邮件发送给最终用户进行审查
最好的方法是什么?
【问题讨论】:
如果'employee_id'+'customer_id'+'timestamp' 很长,并且您对不太可能发生冲突的事物感兴趣,则可以将其替换为哈希。散列的范围和质量将决定冲突的概率。也许最简单的方法是使用builtin hash。假设您的 DataFrame 是 df,并且列是字符串,这是
(df.employee_id + df.customer_id + df.timestamp).apply(hash)
如果您想更好地控制大小和碰撞概率,请参阅this piece on non-crypotgraphic hash functions in Python。
编辑
在 an answer to this question 的基础上,您可以像这样构建 10 个字符的哈希:
import hashlib
df['survey_id'] = (df.employee_id + df.customer_id + df.timestamp).apply(
lambda s: hashlib.md5(s).digest().encode('base64')[: 10])
【讨论】:
如果有人正在寻找模块化功能,请将其保存到文件中以供需要时使用。 (对于 Pandas 数据帧)
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
【讨论】:
我遇到了类似的问题,我就这样解决了:
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 散列,但你真的可以使用任何你需要的散列函数。
【讨论】: