行模式作为PySpark DataFrame中的新列 [英] Mode of row as a new column in PySpark DataFrame

查看:74
本文介绍了行模式作为PySpark DataFrame中的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能基于先前列的最大值添加新列,其中先前列是字符串文字.考虑以下数据框:

Is it possible to add a new column based on the maximum of previous columns where the previous columns are string literals. Consider following dataframe:

df = spark.createDataFrame(
    [
        ('1',25000,"black","black","white"),
        ('2',16000,"red","black","white"),
    ],
    ['ID','cash','colour_body','colour_head','colour_foot']
)

然后目标框架应如下所示:

Then the target frame should look like this:

df = spark.createDataFrame(
    [
        ('1',25000,"black","black","white", "black" ),
        ('2',16000,"red","black","white", "white" ),
    ],
    ['ID','cash','colour_body','colour_head','colour_foot', 'max_v']
)

如果没有最大可检测颜色,则应使用最后一个有效颜色.

If there is no maximum detectable, then the last valid colour should be used.

是否存在某种反制可能性或udf?

Is there some kind of counter possibility available or udf?

推荐答案

statistics.mode周围定义UDF,以使用所需的语义计算行模式:

Define a UDF around statistics.mode to compute the row-wise mode with the required semantics:

import statistics

from pyspark.sql.functions import udf, col
from pyspark.sql.types import StringType

def mode(*x):
    try:
        return statistics.mode(x)
    except statistics.StatisticsError:
        return x[-1]

mode = udf(mode, StringType())

df.withColumn("max_v", mode(*[col(c) for c in df.columns if 'colour' in c])).show()

+---+-----+-----------+-----------+-----------+-----+
| ID| cash|colour_body|colour_head|colour_foot|max_v|
+---+-----+-----------+-----------+-----------+-----+
|  1|25000|      black|      black|      white|black|
|  2|16000|        red|      black|      white|white|
+---+-----+-----------+-----------+-----------+-----+

这篇关于行模式作为PySpark DataFrame中的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆