计算PySpark数据帧列的模式?

2024-03-29 10:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

最终我想要的是一个列的模式,对于数据帧中的所有列。对于其他摘要统计信息,我看到了两个选项:使用DataFrame聚合,或者将DataFrame的列映射到向量的RDD(我也遇到了问题),以及使用MLlib中的colStats。但我不认为模式是一个选项。


Tags: 数据信息dataframe选项模式向量rddmllib
3条回答

模式的问题和中值的问题差不多。虽然计算起来很容易,但计算却相当昂贵。可以使用sort后跟本地和全局聚合,也可以只使用另一个wordcount和filter:

import numpy as np
np.random.seed(1)

df = sc.parallelize([
    (int(x), ) for x in np.random.randint(50, size=10000)
]).toDF(["x"])

cnts = df.groupBy("x").count()
mode = cnts.join(
    cnts.agg(max("count").alias("max_")), col("count") == col("max_")
).limit(1).select("x")
mode.first()[0]
## 0

无论哪种方式,都可能需要对每列进行完全洗牌。

您可以使用Java代码计算列模式,如下所示:

            case MODE:
                Dataset<Row> cnts = ds.groupBy(column).count();
                Dataset<Row> dsMode = cnts.join(
                        cnts.agg(functions.max("count").alias("max_")),
                        functions.col("count").equalTo(functions.col("max_")
                        ));
                Dataset<Row> mode = dsMode.limit(1).select(column);
                replaceValue = ((GenericRowWithSchema) mode.first()).values()[0];
                ds = replaceWithValue(ds, column, replaceValue);
                break;

private static Dataset<Row> replaceWithValue(Dataset<Row> ds, String column, Object replaceValue) {
    return ds.withColumn(column,
            functions.coalesce(functions.col(column), functions.lit(replaceValue)));
}

相关问题 更多 >