我对Pyspark来说还是比较新的。我使用的是2.1.0版。 我试图在更大的数据集上清理一些数据。 我成功地使用了几种技术,例如" dropDuplicates"以及子集和sql函数(distinct,count等)。
然后我遇到了dropna,我认为这可能会简化问题。但是我不明白为什么使用dropna后第3行和第6行仍然存在。 例如:
df = spark.createDataFrame([(1, 'Peter', 1.79, 28,'M', 'Tiler'),
(2, 'Fritz', 1.78, 45,'M', None),
(3, 'Florence', 1.75, None, None, None),
(4, 'Nicola',1.6, 33,'F', 'Dancer'),
(5, 'Gregory', 1.8, 54,'M', 'Teacher'),
(6, 'Steven', 1.82, None, 'M', None),
(7, 'Dagmar', 1.7, 42,'F', 'Nurse'),]
, ['id', 'Name', 'Height', 'Age', 'Gender', 'Occupation'])
df.show()
df.dropna(thresh=2)
df.show()
输出:
+---+--------+------+----+------+----------+
| id| Name|Height| Age|Gender|Occupation|
+---+--------+------+----+------+----------+
| 1| Peter| 1.79| 28| M| Tiler|
| 2| Fritz| 1.78| 45| M| null|
| 3|Florence| 1.75|null| null| null|
| 4| Nicola| 1.6| 33| F| Dancer|
| 5| Gregory| 1.8| 54| M| Teacher|
| 6| Steven| 1.82|null| M| null|
| 7| Dagmar| 1.7| 42| F| Nurse|
+---+--------+------+----+------+----------+
+---+--------+------+----+------+----------+
| id| Name|Height| Age|Gender|Occupation|
+---+--------+------+----+------+----------+
| 1| Peter| 1.79| 28| M| Tiler|
| 2| Fritz| 1.78| 45| M| null|
| 3|Florence| 1.75|null| null| null|
| 4| Nicola| 1.6| 33| F| Dancer|
| 5| Gregory| 1.8| 54| M| Teacher|
| 6| Steven| 1.82|null| M| null|
| 7| Dagmar| 1.7| 42| F| Nurse|
+---+--------+------+----+------+----------+
有人可以建议为什么不删除这些行吗?
pyspark examples根据我假设的用法显示正确的计数。
# threshold
self.assertEqual(self.spark.createDataFrame(
[(u'Alice', None, 80.1)], schema).dropna(thresh=2).count(),
1)
self.assertEqual(self.spark.createDataFrame(
[(u'Alice', None, None)], schema).dropna(thresh=2).count(),
0)
答案 0 :(得分:7)
首先,na
创建一个新的数据帧,因此将其分配给新的df名称,第二个,指定子集以检查要检查哪些列的空值
df2 = df.dropna(thresh=2,subset=('Age','Gender','Occupation'))
df2.show()
输出:
+---+-------+------+---+------+----------+
| id| Name|Height|Age|Gender|Occupation|
+---+-------+------+---+------+----------+
| 1| Peter| 1.79| 28| M| Tiler|
| 2| Fritz| 1.78| 45| M| null|
| 4| Nicola| 1.6| 33| F| Dancer|
| 5|Gregory| 1.8| 54| M| Teacher|
| 7| Dagmar| 1.7| 42| F| Nurse|
+---+-------+------+---+------+----------+
编辑:顺便说一下,thresh=2
单独不起作用,因为阈值意味着删除少于thresh的行(在本例中为2)非空值,但第3行有id,name和height即total 3个非空值和第6行有4个非空值,因此它们不满足thresh=2
条件。您可以尝试thresh=5
答案 1 :(得分:1)
df.dropna(how='all', inplace=True)
df.show()
答案 2 :(得分:0)
您可以尝试以下方法:
df.dropna(how='any').show()