在PySpark需要选择特定的某些行,数据量巨大而没法转到pandas的dataframe操作。
1. 如果内容为数值,可以用between函数筛选。
参考资料:http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column.between
下面的例子,表示筛选出(id >= 5) 及 (id <= 10)的行。
from pyspark.sql.functions import col
df.where(col("id").between(5, 10))
2. 如果选择前多少行,可以用take函数和head函数。
下面的例子,分别表示选择第3行和第5行。
list = df.head(3)
list = df.take(5)
3.选择dataframe中间的特定行数。
而我使用的dataframe前两种方法都没法解决。特点如下:
- 特定列中的内容为字符串,并非数值,不能直接比较大小。
- 所选取数据为中间行,如第10~20行,不能用函数直接选取。
最终的解决方法如下:
- 首先添加行索引,然后选择特定区间内的行索引,从而选取特定中间行。
第一步,添加行索引。
from pyspark.sql.functions import monotonically_increasing_id
dfWithIndex = df.withColumn(“id”,monotonically_increasing_id())
第二步,筛选特定行。
dfWithIndex.select(dfWithIndex.name, dfWithIndex.id.between(50, 100)).show()
成功~