Python pySpark替换特定列中的空值
我下面的代码可以工作,但是它将数据帧中的所有空值替换为“nI”。我只想为要重命名的列替换null。我希望在不硬编码任何列名的情况下执行此操作Python pySpark替换特定列中的空值,python,loops,dataframe,pyspark,null,Python,Loops,Dataframe,Pyspark,Null,我下面的代码可以工作,但是它将数据帧中的所有空值替换为“nI”。我只想为要重命名的列替换null。我希望在不硬编码任何列名的情况下执行此操作 df =datasetMatchedDomains for i in TRUE_matchedAttributeName_List.keys(): df = df.withColumnRenamed(i,TRUE_matchedAttributeName_List[i]); df_final=df.na.fill('NI')
df =datasetMatchedDomains
for i in TRUE_matchedAttributeName_List.keys():
df = df.withColumnRenamed(i,TRUE_matchedAttributeName_List[i]);
df_final=df.na.fill('NI')
display(df_final)
else:
print("clean")
您可以在df.na中提及所需的列子集。你可以找到更多关于 这里有一个例子
df = sc.parallelize([
("portfolio1",None ,"star1"), (None, "Lease", "star2"), ("portfolio2",None, "star3")]).toDF(["a", "b", "c"])
df.show()
+----------+-----+-----+
| a| b| c|
+----------+-----+-----+
|portfolio1| null|star1|
| null|Lease|star2|
|portfolio2| null|star3|
+----------+-----+-----+
TRUE_matchedAttributeName = {'a':'a1'}
subset=[]
for i in TRUE_matchedAttributeName.keys():
subset.append(TRUE_matchedAttributeName[i])
df = df.withColumnRenamed(i, TRUE_matchedAttributeName[i])
df.fillna('source not implemented', subset=subset).show(truncate=False)
+----------------------+-----+-----+
|a1 |b |c |
+----------------------+-----+-----+
|portfolio1 |null |star1|
|source not implemented|Lease|star2|
|portfolio2 |null |star3|
+----------------------+-----+-----+
我不能硬编码任何列名,所以这个建议对我不起作用。我曾考虑使用TRUE_matchedAttributeName_List[I],但在列表理解中很难做到这一点,或者对于每个[I]列,将空值替换为“string”@rupeshreddy@jgtrz,我根据您的要求更新了代码。你现在能查一下吗?我的问题有一个小的修改。将添加广告“附加组件”@rupeshreddy@jgtrz,您在问题中提到,`我只想为正在重命名的
列替换null。您可以在字典中添加列及其重命名
TRUE\u matchedAttributeName`,相应地,您将看到null被“source not implemented”替换为yes。你修改过的代码起作用了。我在帖子中对我的问题补充了一点。