给定下面的数据帧,我们需要从示例中插入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_1
,int_column
中的最低数字是1,正好位于数据帧的末尾,它属于some_id
列中的{
关于如何解决这个问题有什么建议吗?可以使用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)
这是pyspark中的一个解决方案。在
首先定义一个按} ,并按} 定义一个排序。在
my_column
划分的^{int_column
排序。我们将在这个分区上使用^{请注意,
(xx4, 1)
位于按order
排序后的第一行中,如您所述。在现在可以按} ,因为我假设每个
^{pr2}$order
和pivot
对my_column
上的数据帧进行分组。这需要一个聚合函数,所以我将使用^{order
只有一个(some_id, int_column)
对。然后简单地按order
排序并删除该列以获得所需的输出:我们需要一个helper键,使用})
cumcount
创建,然后使用groupby
+apply
(这个部分就像pivot
,或者你可以使用pivot_table
或{如果使用
^{pr2}$pivot
+sort_values
相关问题 更多 >
编程相关推荐