【发布时间】:2021-07-03 20:58:40
【问题描述】:
我有一个数据框。
df = spark.createDataFrame(
[
['3', '2', '3', '30', '0040'],
['2', '5', '7', '6', '0012'],
['5', '8', '1', '73', '0062'],
['4', '2', '5', '2', '0005'],
['5', '2', '4', '12', '0002'],
['8', '3', '2', '23', '0025'],
['2', '2', '8', '23', '0004'],
['5', '5', '4', '12', '0002'],
['8', '2', '2', '23', '0042'],
['2', '2', '8', '23', '0004']
],
['col1', 'col2', 'col3', 'col4', 'col5']
)
df.show()
我想根据以下条件和不同的值添加一个新列。
cond = F.substring(F.col('col5'), 3, 1) == '0'
df1 = df.where(cond)
d_list = df1.select('col2').rdd.map(lambda x: x[0]).distinct().collect()
df2 = df.withColumn('new_col', F.when(F.col('col2').isin(d_list), F.lit('1')).otherwise('0'))
df2.show()
结果:
+----+----+----+----+----+-------+
|col1|col2|col3|col4|col5|new_col|
+----+----+----+----+----+-------+
| 3| 2| 3| 30|0040| 1|
| 2| 5| 7| 6|0012| 1|
| 5| 8| 1| 73|0062| 0|
| 4| 2| 5| 2|0005| 1|
| 5| 2| 4| 12|0002| 1|
| 8| 3| 2| 23|0025| 0|
| 2| 2| 8| 23|0004| 1|
| 5| 5| 4| 12|0002| 1|
| 8| 2| 2| 23|0042| 1|
| 2| 2| 8| 23|0004| 1|
+----+----+----+----+----+-------+
我认为这种方式不适合大型数据集。由于警告,正在寻找没有“collect()”方法的改进或替代方法:use of collect() can lead to poor spark performance
【问题讨论】:
标签: python dataframe apache-spark pyspark apache-spark-sql