gpt4 book ai didi

python - 基于类似于 np.where 的字典替换 Spark DataFrame 中的列值

转载 作者:行者123 更新时间:2023-12-01 00:48:20 25 4
gpt4 key购买 nike

我的数据框看起来像 -

no          city         amount   
1 Kenora 56%
2 Sudbury 23%
3 Kenora 71%
4 Sudbury 41%
5 Kenora 33%
6 Niagara 22%
7 Hamilton 88%

由 92M 条记录组成。我希望我的数据框看起来像 -

no          city         amount      new_city
1 Kenora 56% X
2 Niagara 23% X
3 Kenora 71% X
4 Sudbury 41% Sudbury
5 Ottawa 33% Ottawa
6 Niagara 22% X
7 Hamilton 88% Hamilton

使用python我可以管理它(使用np.where),但在pyspark中没有得到任何结果。有什么帮助吗?

到目前为止我已经完成了 -

#create dictionary
city_dict = {'Kenora':'X','Niagara':'X'}

mapping_expr = create_map([lit(x) for x in chain(*city_dict .items())])

#lookup and replace
df= df.withColumn('new_city', mapping_expr[df['city']])

#But it gives me wrong results.

df.groupBy('new_city').count().show()

new_city count
X 2
null 3

为什么给我空值?

最佳答案

问题在于,对于 city_dict 中未包含的任何城市,mapping_expr 都会返回 null。快速解决方法是使用 coalesce如果 mapping_expr 返回 null 值,则返回 city:

from pyspark.sql.functions import coalesce

#lookup and replace
df1= df.withColumn('new_city', coalesce(mapping_expr[df['city']], df['city']))
df1.show()
#+---+--------+------+--------+
#| no| city|amount|new_city|
#+---+--------+------+--------+
#| 1| Kenora| 56%| X|
#| 2| Sudbury| 23%| Sudbury|
#| 3| Kenora| 71%| X|
#| 4| Sudbury| 41%| Sudbury|
#| 5| Kenora| 33%| X|
#| 6| Niagara| 22%| X|
#| 7|Hamilton| 88%|Hamilton|
#+---+--------+------+--------+

df1.groupBy('new_city').count().show()
#+--------+-----+
#|new_city|count|
#+--------+-----+
#| X| 4|
#|Hamilton| 1|
#| Sudbury| 2|
#+--------+-----+

但是,如果替换值之一为 null,则上述方法将会失败。

在这种情况下,更简单的替代方案可能是使用 pyspark.sql.DataFrame.replace() :

首先使用 withColumn 创建 new_city 作为 city 列中值的副本。

df.withColumn("new_city", df["city"])\
.replace(to_replace=city_dict.keys(), value=city_dict.values(), subset="new_city")\
.groupBy('new_city').count().show()
#+--------+-----+
#|new_city|count|
#+--------+-----+
#| X| 4|
#|Hamilton| 1|
#| Sudbury| 2|
#+--------+-----+

关于python - 基于类似于 np.where 的字典替换 Spark DataFrame 中的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767536/

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