合并两行数据帧

问题描述 投票:0回答:2

让我们说我们有以下数据框:

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

目标是合并具有相同fromto值的行。在上面的示例中,第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

感谢您的任何帮助:)

python pandas
2个回答
2
投票

首先通过fromtonumpy.sort列进行排序,然后通过numpy.sort创建计数器Series,通过GroupBy.cumcountGroupBy.cumcount进行整形,并以DataFrame.set_index进行第二级排序,最后展平[ C0]和DataFrame.set_index并通过DataFrame.unstackDataFrame.unstack转换为列:

DataFrame.sort_index

1
投票

另一个解决方案:

DataFrame.sort_index
© www.soinside.com 2019 - 2024. All rights reserved.