我有一个Spark Dataframe看起来像这样:
| time | col1 | col2 |
|----------------------|
| 123456 | 2 | A |
| 123457 | 4 | B |
| 123458 | 7 | C |
| 123459 | 5 | D |
| 123460 | 3 | E |
| 123461 | 1 | F |
| 123462 | 9 | G |
| 123463 | 8 | H |
| 123464 | 6 | I |
现在,我需要对“ col1”-列进行排序,但其他列必须保持相同的顺序:(使用pyspark)
| time | col1 | col2 | col1_sorted |
|-----------------------------------|
| same | same | same | sorted |
|-----------------------------------|
| 123456 | 2 | A | 1 |
| 123457 | 4 | B | 2 |
| 123458 | 7 | C | 3 |
| 123459 | 5 | D | 4 |
| 123460 | 3 | E | 5 |
| 123461 | 1 | F | 6 |
| 123462 | 9 | G | 7 |
| 123463 | 8 | H | 8 |
| 123464 | 6 | I | 9 |
在此先感谢您的帮助!
对于Spark 2.3.1,您可以尝试pandas_udf,请参见下文(假定原始数据帧按该time
列排序)
from pyspark.sql.functions import pandas_udf, PandasUDFType
from pyspark.sql.types import StructType
schema = StructType.fromJson(df.schema.jsonValue()).add('col1_sorted', 'integer')
@pandas_udf(schema, PandasUDFType.GROUPED_MAP)
def get_col1_sorted(pdf):
return pdf.sort_values(['time']).assign(col1_sorted=sorted(pdf["col1"]))
df.groupby().apply(get_col1_sorted).show()
+------+----+----+-----------+
| time|col1|col2|col1_sorted|
+------+----+----+-----------+
|123456| 2| A| 1|
|123457| 4| B| 2|
|123458| 7| C| 3|
|123459| 5| D| 4|
|123460| 3| E| 5|
|123461| 1| F| 6|
|123462| 9| G| 7|
|123463| 8| H| 8|
|123464| 6| I| 9|
+------+----+----+-----------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句