python - 用列表 Pyspark Dataframe 中的值替换 NA
问题描述
我有一个包含 20 列的 spark 数据框。我想用它们的平均值替换选定列(数字列)中的 NA 值。
我有一个数字列名称的列表,以及它们的平均值列表。我已经编写了以下函数,但我不确定如何将它应用到 Dataframe
NumColNames=['MinTemp','MaxTemp','Rainfall','WindGustSpeed',\
'WindSpeed9am', 'WindSpeed3pm', 'Humidity9am', 'Humidity3pm', 'Pressure9am','Pressure3pm']
avgLst=[12,33,44,21,132,35,22,11,4,55]
def replaceNaNum(df, NumColNames,avgLst):
#iterate through numerical columns names
for column in NumColNames:
#iterate through the aveagres in avgLst
for avg in avgLst:
#replace each NA value in every column with the corresponding average
df=df.withColumn(column, when(df[column] == 'NA',\
avg).otherwise(df[column]))
return df
任何输入表示赞赏,谢谢
解决方案
您可以使用zip
此处绑定列名和相应的平均值,然后从单个循环中提取它们:
for column, avg in zip(NumColNames, avgLst):
df = df.withColumn(column, when(df[column] == 'NA',\
avg).otherwise(df[column]))
推荐阅读
- unity3d - Unity/C# 中出现不寻常的浮点舍入错误?
- python - 使用 igraph 读取数据
- html - Bootstrap html,试图做一个黑暗的桌子
- javascript - Redux 状态返回未定义
- tflearn - 如何使用 tflearn.data_utils.to_categorical (y, nb_classes)
- php - 无法使用 php 更新 Cookie
- haskell - 我不明白列表减法中的类型类约束
- hive - Hortonworks:Hbase、Hive 等用于哪种类型的数据
- css - Handlebars+BootStrap 卡片边框
- git - Git远程推送后打印一条多色消息