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

应用StringIndexer更改PySpark数据帧中的列,pyspark,pyspark-sql,Pyspark,Pyspark Sql,我是pyspark的新手。我想应用StringIndexer将列的值更改为index。 我查看了这篇帖子: 此解决方案将创建一个新列,而不是更新输入列。有没有办法更新current列?我尝试使用相同的名称进行输入和输出,但不起作用 label_stringIdx = StringIndexer(inputCol ="WindGustDir", outputCol = "WindGustDir_index") 您不能简单地更新该列。但你能做的是 使用StringIndexer创建新列 删除原

我是pyspark的新手。我想应用StringIndexer将列的值更改为index。 我查看了这篇帖子:

此解决方案将创建一个新列,而不是更新输入列。有没有办法更新current列?我尝试使用相同的名称进行输入和输出,但不起作用

label_stringIdx = StringIndexer(inputCol ="WindGustDir", outputCol = "WindGustDir_index")

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

  • 使用StringIndexer创建新列

  • 删除原始列

  • 使用原始列的名称重命名新列

您可以使用此代码

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|
# +-----------+-----+

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

  • 使用StringIndexer创建新列

  • 删除原始列

  • 使用原始列的名称重命名新列

您可以使用此代码

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|
# +-----------+-----+