我试图过滤基于如下的RDD:
spark_df = sc.createDataFrame(pandas_df)
spark_df.filter(lambda r: str(r['target']).startswith('good'))
spark_df.take(5)
但是得到了以下错误:
TypeErrorTraceback (most recent call last)
<ipython-input-8-86cfb363dd8b> in <module>()
1 spark_df = sc.createDataFrame(pandas_df)
----> 2 spark_df.filter(lambda r: str(r['target']).startswith('good'))
3 spark_df.take(5)
/usr/local/spark-latest/python/pyspark/sql/dataframe.py in filter(self, condition)
904 jdf = self._jdf.filter(condition._jc)
905 else:
--> 906 raise TypeError("condition should be string or Column")
907 return DataFrame(jdf, self.sql_ctx)
908
TypeError: condition should be string or Column
知道我错过了什么吗?谢谢!
解决方法:
DataFrame.filter是DataFrame.where的别名,它需要一个表达为Column的SQL表达式:
spark_df.filter(col("target").like("good%"))
或等效的SQL字符串:
spark_df.filter("target LIKE 'good%'")
我相信你在这里尝试使用RDD.filter这是完全不同的方法:
spark_df.rdd.filter(lambda r: r['target'].startswith('good'))
并且不会受益于SQL优化.