Ali*_*Ali 5 python list-comprehension replaceall dataframe pyspark
我想用另一个值替换数据框列中的一个值,并且我必须为许多列(假设为 30/100 列)执行此操作
from pyspark.sql.functions import when, lit, col
df = sc.parallelize([(1, "foo", "val"), (2, "bar", "baz"), (3, "baz", "buz")]).toDF(["x", "y", "z"])
df.show()
# I can replace "baz" with Null separaely in column y and z
def replace(column, value):
return when(column != value, column).otherwise(lit(None))
df = df.withColumn("y", replace(col("y"), "baz"))\
.withColumn("z", replace(col("z"), "baz"))
df.show()
Run Code Online (Sandbox Code Playgroud)
我可以在 y 和 z 列中分别用 Null 替换“baz”。但我想对所有列都这样做 - 类似于下面的列表理解方式
[replace(df[col], "baz") for col in df.columns]
Run Code Online (Sandbox Code Playgroud)
由于共有 30/100 列,因此让我们添加更多列以DataFrame
更好地概括它。
# Loading the requisite packages
from pyspark.sql.functions import col, when
df = sc.parallelize([(1,"foo","val","baz","gun","can","baz","buz","oof"),
(2,"bar","baz","baz","baz","got","pet","stu","got"),
(3,"baz","buz","pun","iam","you","omg","sic","baz")]).toDF(["x","y","z","a","b","c","d","e","f"])
df.show()
+---+---+---+---+---+---+---+---+---+
| x| y| z| a| b| c| d| e| f|
+---+---+---+---+---+---+---+---+---+
| 1|foo|val|baz|gun|can|baz|buz|oof|
| 2|bar|baz|baz|baz|got|pet|stu|got|
| 3|baz|buz|pun|iam|you|omg|sic|baz|
+---+---+---+---+---+---+---+---+---+
Run Code Online (Sandbox Code Playgroud)
假设我们想要在除列和之外的所有列中使用replace
baz
with 。用于选择必须完成的那些列。Null
x
a
list comprehensions
replacement
# This contains the list of columns where we apply replace() function
all_column_names = df.columns
print(all_column_names)
['x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f']
columns_to_remove = ['x','a']
columns_for_replacement = [i for i in all_column_names if i not in columns_to_remove]
print(columns_for_replacement)
['y', 'z', 'b', 'c', 'd', 'e', 'f']
Run Code Online (Sandbox Code Playgroud)
最后,使用 using 进行替换when()
,这实际上是 for 子句的假名if
。
# Doing the replacement on all the requisite columns
for i in columns_for_replacement:
df = df.withColumn(i,when((col(i)=='baz'),None).otherwise(col(i)))
df.show()
+---+----+----+---+----+---+----+---+----+
| x| y| z| a| b| c| d| e| f|
+---+----+----+---+----+---+----+---+----+
| 1| foo| val|baz| gun|can|null|buz| oof|
| 2| bar|null|baz|null|got| pet|stu| got|
| 3|null| buz|pun| iam|you| omg|sic|null|
+---+----+----+---+----+---+----+---+----+
Run Code Online (Sandbox Code Playgroud)
UDF
如果可以使用普通子句完成替换,则无需创建并定义函数来执行替换if-else
。UDF
一般来说,这是一种成本高昂的操作,应尽可能避免。