美文网首页
pyspark字符串与索引相互变换

pyspark字符串与索引相互变换

作者: 米斯特芳 | 来源:发表于2021-08-13 14:57 被阅读0次

有时候需要对某列字符串建立索引,然后还原

from pyspark.ml.feature import IndexToString, StringIndexer
from pyspark.sql import SparkSession

spark = SparkSession\
    .builder\
    .appName("IndexToStringExample")\
    .getOrCreate()

df = spark.createDataFrame(
    [(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")],
    ["id", "category"])
# 对字符串建立索引(按出现频率大小给定0,1,2...)
indexer = StringIndexer(inputCol="category", outputCol="categoryIndex")
model = indexer.fit(df)
indexed = model.transform(df)

print("Transformed string column '%s' to indexed column '%s'"
      % (indexer.getInputCol(), indexer.getOutputCol()))
indexed.show()

print("StringIndexer will store labels in output column metadata\n")
# 将索引还原为字符串
converter = IndexToString(inputCol="categoryIndex", outputCol="originalCategory")
converted = converter.transform(indexed)

print("Transformed indexed column '%s' back to original string column '%s' using "
      "labels in metadata" % (converter.getInputCol(), converter.getOutputCol()))
converted.select("id", "categoryIndex", "originalCategory").show()

相关文章

  • pyspark字符串与索引相互变换

    有时候需要对某列字符串建立索引,然后还原

  • String

    字符串索引 插入与删除 Substring

  • 字符串(三)

    字符串的索引与分片 字符串可以通过运算符[]进行索引与分片,字符串中每个字符都对应两个编号(也称下标),如下图所示...

  • 字符串

    下标索引 字符串中‘下标’的使用列表与元组支持下标索引好理解,字符串实际上就是字符的数组,所以也支持下标索引。 如...

  • pyspark DCT(离散余弦变换)

    DCT:将时域的N维实数序列转换成频域的N维实数序列常用于信号处理和图像处理,对信号和图像(包括静止图像和运动图像...

  • python 字符串

    字符串操作 + 字符串连接操作 * 字符串复制操作 [] 字符串索引 通过索引访问指定位置的字符,索引从头(0)...

  • iOS NSMutableArray obj与另一个obj交

    意思为:索引为3的与索引为2的object相互交换 [array exchangeObjectAtIndex:3 ...

  • 不适用索引的SQL

    索引列参与计算 索引列使用了函数 索引列使用了Like %XXX 字符串列与数字直接比较 尽量避免OR操作

  • shell之字符串

    获取字符串长度:${#变量} 与 expr length 变量 获取字符串索引位置:expr index变量 获取...

  • 字符串基础语法

    索引访问 字符串[索引] 切片访问字符串[开始,结束,步长] 判断字符串是否只包含空格 字符串.isspace...

网友评论

      本文标题:pyspark字符串与索引相互变换

      本文链接:https://www.haomeiwen.com/subject/orodbltx.html