我有以下spark 源数据帧:

df
col1 col2 col3
1      2    3
4    None   6
7      8   None

我想用它们所在行的平均值替换None(或Null)值. 输出将如下所示:

df_result
col1 col2 col3
1      2    3
4      5    6
7      8   7.5

我try 过的所有方法都会导致错误"Column is not Iterable"或"Inid Argument,Not a String or Column". 非常感谢您的帮助!

推荐答案

100

try 使用100个函数,并计算数组中101个函数的数量.

然后计算出mean of the elements.

最后是divide101的平均值.

100

df.show(10,False)
#+----+----+----+
#|col1|col2|col3|
#+----+----+----+
#|1   |2   |3   |
#|4   |null|6   |
#|7   |8   |null|
#+----+----+----+

#add nulls_count filed to check how many null values are there in all the columns
#cast all columns as an array
#sum_elems as sum of all elements of array
#calculate the mean based on non null values
df1 = df.withColumn("nulls_count",size(filter(array(*[isnull(col(c)) for c in df.columns]), lambda x: x))).\
  withColumn("arr_vals",array(*[coalesce(col(c),lit(0)) for c in df.columns])).\
  withColumn("sum_elems",expr("aggregate(arr_vals,cast(0 as bigint),(acc, x) -> acc + x)")).\
  withColumn("mean_val",expr('round(sum_elems/((size(arr_vals))-nulls_count),1)'))

df1.select([when(col(c).isNull(), col("mean_val")).otherwise(col(c)).alias(c) for c in df.columns]).show(10,False)
#+----+----+----+
#|col1|col2|col3|
#+----+----+----+
#|1.0 |2.0 |3.0 |
#|4.0 |5.0 |6.0 |
#|7.0 |8.0 |7.5 |
#+----+----+----+

Python相关问答推荐

合并其中一个具有重叠范围的两个框架的最佳方法是什么?

如何在Python中增量更新DF

如何处理必须存在于环境中但无法安装的Python项目依赖项?

已删除的构造函数调用另一个构造函数

Google Drive API获取文件计量数据

具有症状的分段函数:如何仅针对某些输入值定义函数?

在Python和matlab中显示不同 colored颜色 的图像

Odoo 14 hr. emergency.public内的二进制字段

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

处理(潜在)不断增长的任务队列的并行/并行方法

优化pytorch函数以消除for循环

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

CommandeError:模块numba没有属性generated_jit''''

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

Polars asof在下一个可用日期加入

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

将标签移动到matplotlib饼图中楔形块的开始处

如何获取Python synsets列表的第一个内容?

BeautifulSoup:超过24个字符(从a到z)的迭代失败:降低了首次深入了解数据集的复杂性:

Django Table—如果项目是唯一的,则单行