【问题标题】:How to place column name as variable when using Stringindexer in Pyspark在 Pyspark 中使用 Stringindexer 时如何将列名作为变量
【发布时间】:2021-05-10 14:18:58
【问题描述】:
{simpleDF.columns 
 #output :['color', 'lab', 'value1', 'value2']
 indexer = simpleDF.select('lab')

 from pyspark.ml.feature import StringIndexer
 # Let us create an object of the class StringIndexer
 lblindexer=StringIndexer().setInputCol(indexer).setOutputCol("LabelIndexed")
 idxRes=lblindexer.fit(simpleDF).transform(simpleDF)

 idxRes.show(5)}

这行代码运行良好,但我希望它更通用

 #lblindexer=StringIndexer().setInputCol('lab').setOutputCol("LabelIndexed")

得到错误: TypeError:为参数“inputCol”提供的参数值无效。无法将 转换为字符串类型

【问题讨论】:

  • 您的注释代码不起作用正在将字符串传递给 setInputCol。 setInputCol 是否接受字符串?当您将它传递给 simpleDf.select(). 时,看起来您已经开始工作了

标签: apache-spark pyspark apache-spark-ml


【解决方案1】:

使用输入列的列名,而不是数据框:

lblindexer=StringIndexer().setInputCol('lab').setOutputCol("LabelIndexed")

如果要使用变量,

indexer = 'lab'
lblindexer=StringIndexer().setInputCol(indexer).setOutputCol("LabelIndexed")

【讨论】:

  • 我希望它更普遍地使用这就是为什么它需要通过变量使用。
  • @AizazYousaf 第二个代码对你有用吗?
  • 认为用户从前端选择了列,我想在 stringindexer 中传递这个列名
猜你喜欢
  • 2016-08-24
  • 1970-01-01
  • 2021-08-31
  • 2019-02-24
  • 2021-11-19
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多