gpt4 book ai didi

python - 根据列的字符串值将数字列添加到 pyspark DataFrame

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:33 25 4
gpt4 key购买 nike

我有一个从 JSON 文件构建的 DataFrame:

{ "1": "a b c d e f", "2": 1, "type": "type1"}
{ "1": "a b c b c", "2": 2, "type": "type1"}
{"1": "d d a b c", "2": 3, "type": "type2"}
...

我正在设计一个朴素贝叶斯分类器,这样的 DataFrame 就是我的训练集:分类器将使用从字段 1 中提取的特征,类(标签)由字段 type< 给出/em>.

我的问题是在拟合模型时出现此错误:

pyspark.sql.utils.IllegalArgumentException: u'requirement failed: Column type must be of type DoubleType but was actually StringType.'

表示标签字段必须是数字。为了解决这个问题,我试图通过字典将字符串值映射为数值

grouped = df.groupBy(df.type).agg({'*': 'count'}).persist()
types = {row.type: grouped.collect().index(row) for row in grouped.collect()}

然后我们的想法是向 DataFrame 添加一个新列,其数值对应于它的字符串值:

df = df.withColumn('type_numeric', types[df.type])

这当然失败了,所以我想知道是否有人对如何实现这一目标有更好的想法或建议。

最佳答案

我已经通过使用 DataFrame 的 StringIndexer 解决了问题。

string_indexer = StringIndexer(inputCol='type', outputCol='type_numeric')
rescaled_data_numeric = string_indexer.fit(df).transform(df)

关于python - 根据列的字符串值将数字列添加到 pyspark DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35415178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com