首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >应用StringIndexer更改PySpark数据中的列

应用StringIndexer更改PySpark数据中的列
EN

Stack Overflow用户
提问于 2019-10-13 23:26:45
回答 1查看 1.9K关注 0票数 1

我对火种很陌生。我想应用StringIndexer将列的值更改为索引。我查看了这篇文章:Apply StringIndexer to several columns in a PySpark Dataframe

此解决方案将创建一个新列,而不是更新输入列。是否有更新当前列的方法?我试图在输入和输出中使用相同的名称,但它不起作用。

代码语言:javascript
运行
复制
label_stringIdx = StringIndexer(inputCol ="WindGustDir", outputCol = "WindGustDir_index")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-14 05:46:25

不能简单地更新该列。但你能做的是

使用StringIndexer

  • delete
  • 创建一个新列原始列
  • 用原始列

的名称重命名新列

您可以使用以下代码

代码语言:javascript
运行
复制
from pyspark.ml.feature import StringIndexer
import pyspark.sql.functions as F


df = spark.createDataFrame([['a', 1], ['b', 1], ['c', 2], ['b', 5]], ['WindGustDir', 'value'])
df.show()
# +-----------+-----+
# |WindGustDir|value|
# +-----------+-----+
# |          a|    1|
# |          b|    1|
# |          c|    2|
# |          b|    5|
# +-----------+-----+

# 1. create new column
label_stringIdx = StringIndexer(inputCol ="WindGustDir", outputCol = "WindGustDir_index")
label_stringIdx_model = label_stringIdx.fit(df)
df = label_stringIdx_model.transform(df)

# 2. delete original column
df = df.drop("WindGustDir")

# 3. rename new column
to_rename = ['WindGustDir_index', 'value']
replace_with = ['WindGustDir', 'value']
mapping = dict(zip(to_rename, replace_with))
df = df.select([F.col(c).alias(mapping.get(c, c)) for c in to_rename])

df.show()

# +-----------+-----+
# |WindGustDir|value|
# +-----------+-----+
# |        1.0|    1|
# |        0.0|    1|
# |        2.0|    2|
# |        0.0|    5|
# +-----------+-----+
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58368568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档