我有一个Dataframe,需要将同一组的行转换为列。基本上就是这些。下面是我的df。
+------------+-------+-----+-------+
|Customer |ID |unit |order |
+------------+-------+-----+-------+
|John |123 |00015|1 |
|John |123 |00016|2 |
|John |345 |00205|3 |
|John |345 |00206|4 |
|John |789 |00283|5 |
|John |789 |00284|6 |
+------------+-------+-----+-------+
我需要的结果数据为上述。。
+--------+-------+--------+----------+--------+--------+-----------+--------+-------+----------+
|state | ID_1 | unit_1 |seq_num_1 | ID_2 | unit_2 | seq_num_2 | ID_3 |unit_3 |seq_num_3 |
+--------+-------+--------+----------+--------+--------+-----------+--------+-------+----------+
|John | 123 | 00015 | 1 | 345 | 00205 | 3 | 789 |00283 | 5 |
|John | 123 | 00016 | 2 | 345 | 00206 | 4 | 789 |00284 | 6 |
+--------+-------+--------+----------+--------+--------+-----------+--------+-------+----------+
我尝试使用groupby和pivot()函数,但它的抛出错误表明找到了较大的pivot值。有没有不使用pivot()函数就能得到结果的方法..非常感谢您的帮助。谢谢。
3条答案
按热度按时间vd2z7a6w1#
这看起来像是一个典型的使用dense_rank()聚合函数创建泛型序列的例子(
dr
在下面的代码)中,在每个客户组下使用不同的ID,然后按此顺序旋转。我们可以做类似的事情order
列,以便可以在groupby中使用:添加两个窗规格:
w1
在客户和w2
获取同一客户和同一id下订单的行号()。基于上述两个WinSpec添加两个新列:
dr
(密级)和sid
(行号)找到
max(dr)
,这样我们就可以预先定义要以其为中心的列表range(1,N+1)
(这将提高pivot
方法)。groupby公司
Customer
,sid
以…为轴心dr
然后进行聚合:如果需要,请重命名列名:
jpfvwuh42#
下面是我的解决方案。。做排名然后把结果展平。
aelbi1ox3#
可能有多种方法可以做到这一点,但Pandas自定义项可以是这样一种方式。以下是一个基于您的数据的玩具示例: