应用
我有一个具有以下结构的数据帧:
Col1 Col2 Col3 Col4 Col5 Col6
Apple 1.0
Apple 1.0 Fruit Green 0.99 OK
Apple Green 0.99
Apple 0.99
Banana 2.0 Fruit Yellow 1.29
Banana 2.0
Banana 2.0 Fruit
Coconut 2.2
Coconut Fruit
Coconut 2.2 Fruit Brown OK
我需要保持具有更多信息值的行。
这个例子中我需要的数据帧:
Col1 Col2 Col3 Col4 Col5 Col6
Apple 1.0 Fruit Green 0.99 OK
Banana 2.0 Fruit Yellow 1.29
Coconut 2.2 Fruit Brown OK
我需要将这个逻辑应用于许多数据帧(pyspark(。
编辑:No Informed值不是null,只是没有字符"(没有空格("的列。
对于每个值,将其转换为布尔值,指示单元格是否已填充。每行求和。保留总和最大的行。
这是代码,其中df
是您的输入数据帧。
nb_col_filled = df.notna().sum(axis=1)
result_df = df[nb_col_filled==nb_col_filled.max()]
只需使用max
即可获得;max";每列的值
样本数据
df = spark.createDataFrame([
( 'Apple' , '1.0', '', '', '', ''),
( 'Apple' , '1.0', 'Fruit', 'Green', '0.99', 'OK'),
( 'Apple' , '', '', 'Green', '0.99', ''),
( 'Apple' , '0.99', '', '', '', ''),
( 'Banana', '2.0', 'Fruit', 'Yello', '1.29', ''),
( 'Banana', '2.0', '', '', '', ''),
( 'Banana', '2.0', 'Fruit', '', '', ''),
('Coconut', '2.2', '', '', '', ''),
('Coconut', '', 'Fruit', '', '', ''),
('Coconut', '2.2', 'Fruit', 'Brown', '', 'OK'),
], ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6'])
应用max
(df
.groupBy('Col1')
.agg(
F.max('Col2').alias('Col2'),
F.max('Col3').alias('Col3'),
F.max('Col4').alias('Col4'),
F.max('Col5').alias('Col5'),
F.max('Col6').alias('Col6'),
)
.show()
)
+-------+----+-----+-----+----+----+
| Col1|Col2| Col3| Col4|Col5|Col6|
+-------+----+-----+-----+----+----+
| Apple| 1.0|Fruit|Green|0.99| OK|
| Banana| 2.0|Fruit|Yello|1.29| |
|Coconut| 2.2|Fruit|Brown| | OK|
+-------+----+-----+-----+----+----+