让我们说我们有以下数据框:
df = pd.DataFrame(
data={
'from': [103, 102, 104, 105],
'to': [104, 105, 103, 102],
'id': [1] * 4,
'p': [415, 1203.11, -414.35, -1197.37],
'q': [0, -395.44, 62.23, 489.83]
})
或
from to id p q
0 103 104 1 415.00 0.00
1 102 105 1 1203.11 -395.44
2 104 103 1 -414.35 62.23
3 105 102 1 -1197.37 489.83
目标是合并具有相同from
和to
值的行。在上面的示例中,第0行和第2行以及第1行和第3行需要合并。
输出应该如下:
from to id p q p1 q1
0 103 104 1 415.00 0.00 -414.35 62.23
1 102 105 1 1203.11 -395.44 -1197.37 489.83
当然,以下内容也是可以接受的:
from to id p q p1 q1
0 104 103 1 -414.35 62.23 415.00 0.00
1 105 102 1 -1197.37 489.83 1203.11 -395.44
感谢您的任何帮助:)
首先通过from
对to
和numpy.sort
列进行排序,然后通过numpy.sort
创建计数器Series
,通过GroupBy.cumcount
和GroupBy.cumcount
进行整形,并以DataFrame.set_index
进行第二级排序,最后展平[ C0]和DataFrame.set_index
并通过DataFrame.unstack
将DataFrame.unstack
转换为列:
DataFrame.sort_index
另一个解决方案:
DataFrame.sort_index