gpt4 book ai didi

python - 用 DataFrame 中的 None/null 值替换空字符串

转载 作者:IT老高 更新时间:2023-10-28 20:37:19 26 4
gpt4 key购买 nike

我有一个 Spark 1.5.0 DataFrame在同一列中混合使用 null 和空字符串。我想将所有列中的所有空字符串转换为 null (None,在 Python 中)。 DataFrame 可能有数百列,因此我试图避免对每一列进行硬编码操作。

请参阅下面的尝试,这会导致错误。

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

## Create a test DataFrame
testDF = sqlContext.createDataFrame([Row(col1='foo', col2=1), Row(col1='', col2=2), Row(col1=None, col2='')])
testDF.show()
## +----+----+
## |col1|col2|
## +----+----+
## | foo| 1|
## | | 2|
## |null|null|
## +----+----+

## Try to replace an empty string with None/null
testDF.replace('', None).show()
## ValueError: value should be a float, int, long, string, list, or tuple

## A string value of null (obviously) doesn't work...
testDF.replace('', 'null').na.drop(subset='col1').show()
## +----+----+
## |col1|col2|
## +----+----+
## | foo| 1|
## |null| 2|
## +----+----+

最佳答案

就这么简单:

from pyspark.sql.functions import col, when

def blank_as_null(x):
return when(col(x) != "", col(x)).otherwise(None)

dfWithEmptyReplaced = testDF.withColumn("col1", blank_as_null("col1"))

dfWithEmptyReplaced.show()
## +----+----+
## |col1|col2|
## +----+----+
## | foo| 1|
## |null| 2|
## |null|null|
## +----+----+

dfWithEmptyReplaced.na.drop().show()
## +----+----+
## |col1|col2|
## +----+----+
## | foo| 1|
## +----+----+

如果您想填充多列,例如可以减少:

to_convert = set([...]) # Some set of columns

reduce(lambda df, x: df.withColumn(x, blank_as_null(x)), to_convert, testDF)

或使用理解:

exprs = [
blank_as_null(x).alias(x) if x in to_convert else x for x in testDF.columns]

testDF.select(*exprs)

如果要专门对字符串字段进行操作,请查看the answerrobin-loxley .

关于python - 用 DataFrame 中的 None/null 值替换空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33287886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com