插入一个DataFrame列并根据PySpark或Pandas中的另一列进行排序

2024-09-28 03:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

给定下面的数据帧,我们需要从示例中插入my_column值,并将它们用作单独的列,然后按属于每个some_id列的int_column值按降序排序。例如:

+--------------------+-----------+------------------+
|          some_id   | my_column |      int_column  |
+--------------------+-----------+------------------+
|xx1                 |id_1       |           3      |
|xx1                 |id_2       |           4      |
|xx1                 |id_3       |           5      |
|xx2                 |id_1       |           6      |
|xx2                 |id_2       |           1      |
|xx2                 |id_3       |           3      |
|xx3                 |id_1       |           4      |
|xx3                 |id_2       |           8      |
|xx3                 |id_3       |           9      |
|xx4                 |id_1       |           1      |
+--------------------+-----------+------------------+

预期产量:

^{pr2}$

如您所见,对于id_1int_column中的最低数字是1,正好位于数据帧的末尾,它属于some_id列中的{},下一个值是3、4和6,分别属于xx1、xx3和xx2。在

关于如何解决这个问题有什么建议吗?可以使用PySpark或Pandas。在

复制输入数据帧的代码:

import pandas as pd

data = {'some_id': ['xx1', 'xx1', 'xx1', 'xx2', 'xx2', 'xx2', 'xx3', 'xx3', 'xx3', 'xx4'], \
        'my_column' : ['id_1', 'id_2', 'id_3', 'id_1', 'id_2', 'id_3', 'id_1', 'id_2', 'id_3', 'id_1'],\
       'int_column' : [3, 4, 5, 6 , 1, 3, 4, 8, 9, 1]}

df = pd.DataFrame.from_dict(data)

Tags: 数据id示例data排序mycolumnsome
2条回答

这是pyspark中的一个解决方案。在

首先定义一个按my_column划分的^{},并按int_column排序。我们将在这个分区上使用^{}定义一个排序。在

from pyspark.sql import Window
import pyspark.sql.functions as f
w = Window.partitionBy("my_column").orderBy("int_column")
df.withColumn("order", f.row_number().over(w)).sort("order").show()
#+   -+    -+     +  -+
#|some_id|my_column|int_column|order|
#+   -+    -+     +  -+
#|    xx4|     id_1|         1|    1|
#|    xx2|     id_2|         1|    1|
#|    xx2|     id_3|         3|    1|
#|    xx1|     id_2|         4|    2|
#|    xx1|     id_1|         3|    2|
#|    xx1|     id_3|         5|    2|
#|    xx3|     id_2|         8|    3|
#|    xx3|     id_3|         9|    3|
#|    xx3|     id_1|         4|    3|
#|    xx2|     id_1|         6|    4|
#+   -+    -+     +  -+

请注意,(xx4, 1)位于按order排序后的第一行中,如您所述。在

现在可以按orderpivotmy_column上的数据帧进行分组。这需要一个聚合函数,所以我将使用^{},因为我假设每个order只有一个(some_id, int_column)对。然后简单地按order排序并删除该列以获得所需的输出:

^{pr2}$

我们需要一个helper键,使用cumcount创建,然后使用groupby+apply(这个部分就像pivot,或者你可以使用pivot_table或{})

df=df.assign(key=df.groupby('my_column').cumcount())
df.groupby(['key','my_column']).apply(lambda x : list(zip(x['some_id'],x['int_column']))[0]).unstack()
Out[378]: 
my_column      id_1      id_2      id_3
key                                    
0          (xx1, 3)  (xx1, 4)  (xx1, 5)
1          (xx2, 6)  (xx2, 1)  (xx2, 3)
2          (xx3, 4)  (xx3, 8)  (xx3, 9)
3          (xx4, 1)      None      None

如果使用pivot+sort_values

^{pr2}$

相关问题 更多 >

    热门问题