PySpark - 根据条件填充特定行
PySpark - Fillna specific rows based on condition
我想替换数据框中的空值,但仅限于符合特定条件的行。
我有这个数据框:
A|B |C |D |
1|null|null|null|
2|null|null|null|
2|null|null|null|
2|null|null|null|
5|null|null|null|
我想这样做:
A|B |C |D |
1|null|null|null|
2|x |x |x |
2|x |x |x |
2|x |x |x |
5|null|null|null|
我的情况
因此,应替换 A 列中编号为 2 的所有行。
A、B、C、D 列是动态的,它们的编号和名称会发生变化。
我还希望能够 select 所有行,而不仅仅是被替换的行。
我试过的
我尝试使用 df.where 和 fillna,但它并没有保留所有行。
我也考虑过使用 withColumn,但我只知道 A 列,所有其他列都会在每次执行时发生变化。
适应的解决方案:
df.select("A",
*[
when(col("A") == '2',
coalesce(col(c),
lit('0').cast(df.schema[c].dataType))
).otherwise(col(c)).alias(c)
for c in cols_to_replace
])
使用pyspark.sql.functions.when
with pyspark.sql.functions.coalesce
:
from pyspark.sql.functions import coalesce, col, lit, when
cols_to_replace = df.columns[1:]
df.select(
"A",
*[
when(col("A")==2, coalesce(col(c), lit("x"))).otherwise(col(c)).alias(c)
for c in cols_to_replace
]
).show()
#+---+----+----+----+
#| A| B| C| D|
#+---+----+----+----+
#| 1|null|null|null|
#| 2| x| x| x|
#| 2| x| x| x|
#| 2| x| x| x|
#| 5|null|null|null|
#+---+----+----+----+
在列表理解中,您检查 A
的值是否为 2
。如果是,则合并列的值和文字 x
。这会将 null
s 替换为 x
。否则,保持相同的列值。
我想替换数据框中的空值,但仅限于符合特定条件的行。
我有这个数据框:
A|B |C |D |
1|null|null|null|
2|null|null|null|
2|null|null|null|
2|null|null|null|
5|null|null|null|
我想这样做:
A|B |C |D |
1|null|null|null|
2|x |x |x |
2|x |x |x |
2|x |x |x |
5|null|null|null|
我的情况
因此,应替换 A 列中编号为 2 的所有行。
A、B、C、D 列是动态的,它们的编号和名称会发生变化。
我还希望能够 select 所有行,而不仅仅是被替换的行。
我试过的
我尝试使用 df.where 和 fillna,但它并没有保留所有行。
我也考虑过使用 withColumn,但我只知道 A 列,所有其他列都会在每次执行时发生变化。
适应的解决方案:
df.select("A",
*[
when(col("A") == '2',
coalesce(col(c),
lit('0').cast(df.schema[c].dataType))
).otherwise(col(c)).alias(c)
for c in cols_to_replace
])
使用pyspark.sql.functions.when
with pyspark.sql.functions.coalesce
:
from pyspark.sql.functions import coalesce, col, lit, when
cols_to_replace = df.columns[1:]
df.select(
"A",
*[
when(col("A")==2, coalesce(col(c), lit("x"))).otherwise(col(c)).alias(c)
for c in cols_to_replace
]
).show()
#+---+----+----+----+
#| A| B| C| D|
#+---+----+----+----+
#| 1|null|null|null|
#| 2| x| x| x|
#| 2| x| x| x|
#| 2| x| x| x|
#| 5|null|null|null|
#+---+----+----+----+
在列表理解中,您检查 A
的值是否为 2
。如果是,则合并列的值和文字 x
。这会将 null
s 替换为 x
。否则,保持相同的列值。