Python 基于列的字符串值向pyspark数据帧添加数字列

Python 基于列的字符串值向pyspark数据帧添加数字列,python,dataframe,pyspark,Python,Dataframe,Pyspark,我已经从JSON文件构建了一个数据框架: { "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"} ... 我正在设计一个朴素贝叶斯分类器,这样的数据帧就是我的训练集:分类器将使用从字段1提取的特征,类(标签)由字段类型给出 我的问题是在拟合模型时出现以下错误: pyspark.sq

我已经从JSON文件构建了一个数据框架:

{ "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"}
...
我正在设计一个朴素贝叶斯分类器,这样的数据帧就是我的训练集:分类器将使用从字段1提取的特征,类(标签)由字段类型给出

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

pyspark.sql.utils.IllegalArgumentException:u“要求失败:列类型必须是DoubleType类型,但实际上是StringType。”

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

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])

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

我已经通过使用StringIndexer对数据帧进行索引解决了这个问题

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

您好,请先写下您的问题,然后写下您期望的结果,最后写下错误消息