根据条件从pyspark数据框中删除行

16

我有一个包含两列的数据框:

+--------+-----+
|    col1| col2|
+--------+-----+
|22      | 12.2|
|1       |  2.1|
|5       | 52.1|
|2       | 62.9|
|77      | 33.3|

我想创建一个新的数据框,只选取“col1的值”大于“col2的值”的行。

仅供参考,col1 的类型为 long,col2 的类型为 double

结果应该像这样:

+--------+----+
|    col1|col2|
+--------+----+
|22      |12.2|
|77      |33.3|
4个回答

22

我认为最好的方法是简单地使用“筛选器”。

df_filtered=df.filter(df.col1>df.col2)
df_filtered.show()

+--------+----+
|    col1|col2|
+--------+----+
|22      |12.2|
|77      |33.3|

10
< p >另一种可能的方法是使用DF的< code>where函数。

例如:


例如:

val output = df.where("col1>col2")

将会给您期望的结果:

+----+----+
|col1|col2|
+----+----+
|  22|12.2|
|  77|33.3|
+----+----+

7

如其他人所述,保留基于条件的行的最佳方法是使用filter

回答标题中提出的问题,一种根据条件删除行的选项是在Pyspark中使用left_anti join。例如,要删除所有具有col1>col2的行,请使用:

rows_to_delete = df.filter(df.col1>df.col2)

df_with_rows_deleted = df.join(rows_to_delete, on=[key_column], how='left_anti')

1
你可以使用sqlContext来简化这个挑战。
首先,注册为临时表,例如: df.createOrReplaceTempView("tbl1") 然后运行如下的sql语句: sqlContext.sql("select * from tbl1 where col1 > col2")

你可以使用以下代码创建sqlContext:from pyspark.sql import SQLContext sqlContext = SQLContext.getOrCreate(sc).sparkSession - jagath
谢谢!我正确理解sqlContext.sql(...)会返回一个数据框,对吗? - LDropl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接