将数据帧的每一行转换为字符串

问题描述 投票:0回答:1

我正在尝试使用pyspark中的hashlib.md5为数据帧生成哈希码。它只接受一个字符串来生成哈希码。

我需要将数据帧的每一行转换为字符串。

我尝试使用concat_ws函数连接所有列并使其成为字符串但没有结果。

我的数据框有Id, name, marks

我试过了:

str=df.select(concat_ws("id","name","marks"))

print(hashlib.md5(str.encode(encoding='utf_8', errors='strict')).hexdigest())

我收到了这个错误:

AttributeError: 'DataFrame' object has no attribute 'encode'
apache-spark pyspark apache-spark-sql pyspark-sql
1个回答
1
投票

你能试一下吗

df.select("colname").rdd.map(lambda x: hashlib.md5(str(x).encode(encoding='utf_8', errors='strict')).hexdigest()).collect()

你应该看到类似的东西

['1dd55a7d40667d697743612f826b71e1', '64a537f89bd95f34374b619452b1a5ab']

在你的情况下,

df.select(expr("concat_ws(id,name,marks)").alias("mycolumn")).rdd.map(lambda x: hashlib.md5(str(x).encode(encoding='utf_8', errors='strict')).hexdigest()).collect()
© www.soinside.com 2019 - 2024. All rights reserved.