在Pyspark中将数据框列转换为类别类型

6

我有一个数据框df,我想把其中一些列转换为类别类型。使用pandas,我可以按照以下方式完成:

    for col in categorical_collist:
        df[col] = df[col].astype('category')

我想在Pyspark中进行列转换。我该怎么做?

我尝试在Pyspark中使用以下代码。但在操作期间,它没有给出我预期的输出。

from pyspark.sql.types import StringType
for col in categorical_collist:
    df = df.withColumn(col, df[col].cast(StringType()))
1个回答

0
在PySpark中,您可以使用DataFrame的withColumn()方法将列转换为分类类型。
from pyspark.sql.functions import col

categorical_collist = [...] # list of categorical columns

for col_name in categorical_collist:
    df = df.withColumn(col_name, col(col_name).cast("string").cast("category"))

我们首先从pyspark.sql.functions中导入col()函数,该函数用于按名称引用列。
然后,我们循环遍历categorical_collist中的列名列表,并针对每个列,使用withColumn()方法创建一个具有相同名称的新列,但将其转换为字符串,然后再转换为分类类型。
请注意,在PySpark中,您需要先将其转换为字符串,然后再转换为分类类型,因为cast()方法期望输入为字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接