python - pyspark 数据框为每一行获得第二低的值
问题描述
如果有人有想法,我想查询如何在 pyspark 中的 Dataframe 行中获得第二低的值。
例如:
输入数据框:
Col1 Col2 Col3 Col4
83 32 14 62
63 32 74 55
13 88 6 46
预期输出:
Col1 Col2 Col3 Col4 Res
83 32 14 62 32
63 32 74 55 55
13 88 6 46 13
解决方案
我们可以使用concat_ws
函数来连接该行的所有列,然后用于split
创建一个数组。
使用array_sort
函数在数组中排序并提取second element[1]
数组。
Example:
from pyspark.sql.functions import *
df=spark.createDataFrame([('83','32','14','62'),('63','32','74','55'),('13','88','6','46')],['Col1','Col2','Col3','Col4'])
df.selectExpr("array_sort(split(concat_ws(',',Col1,Col2,Col3,Col4),','))[1] Res").show()
#+---+
#|Res|
#+---+
#|32 |
#|55 |
#|13 |
#+---+
More Dynamic Way:
df.selectExpr("array_sort(split(concat_ws(',',*),','))[1]").show()
#+---+
#|Res|
#+---+
#|32 |
#|55 |
#|13 |
#+---+
EDIT:
#adding Res column to the dataframe
df1=df.selectExpr("*","array_sort(split(concat_ws(',',*),','))[1] Res")
df1.show()
#+----+----+----+----+---+
#|Col1|Col2|Col3|Col4|Res|
#+----+----+----+----+---+
#| 83| 32| 14| 62| 32|
#| 63| 32| 74| 55| 55|
#| 13| 88| 6| 46| 46|
#+----+----+----+----+---+
推荐阅读
- dom - 使用 PureScript 从 div 中清除所有子元素
- javascript - 访问框架集框架之间的选择选项标签时出现 IE 11 权限问题
- django - 带有 websockets 的 Django - Uvicorn + Nginx
- r - 使用 model.matrix() 创建虚拟变量
- grpc - ServerAsyncReaderWriter.Write 不是执行 tcp_write 的异步
- javascript - Mocha:设置超时使测试串行
- python - 数字根和持久性功能
- javascript - 基于父组件 props 为子组件添加额外样式
- c# - 如何使用.net core c#保存pfx文件
- java - 在 Recycle View 上设置视图适配器会使应用程序崩溃