使用Python Pandas重塑(融合?)数据并同时合并列。

4

我有以下数据帧:

df = pd.DataFrame({'Date':['01/01/2021','08/01/2021'],
                  'a_score':[7,3],
                  'b_score':[2,4],
                  'a':['north','south'],
                  'b':['south','north']})

Date        a_score b_score a       b
01/01/2021  7       2       north   south
08/01/2021  3       4       south   north

我应该如何最好地调整格式,将a和b两列数据堆叠在一起,同时将a_score和b_score也堆叠在一起?期望的输出如下:
Date        Region  score   score_against
01/01/2021  north   7       2
01/01/2021  south   2       7
08/01/2021  north   4       3
08/01/2021  south   3       4

非常感谢。
1个回答

4
你可以获取内部的numpy数组并对其进行操作,以获得所需的结果:
import numpy as np
new_df = pd.DataFrame(np.vstack((df.values,df.values[:, [0,2, 1, 4,3]]))[:, :-1], columns = ['Date', 'score', 'score_against', 'Region'])

输出:

         Date score score_against Region
0  01/01/2021     7             2  north
1  08/01/2021     3             4  south
2  01/01/2021     2             7  south
3  08/01/2021     4             3  north

解释:

np.vstack((df.values,df.values[:, [0,2, 1, 4,3]]))[:, :-1]

取出内部的numpy数组(df.values),交换列,并将其与原始numpy数组垂直堆叠:

array([['01/01/2021', 7, 2, 'north'],
       ['08/01/2021', 3, 4, 'south'],
       ['01/01/2021', 2, 7, 'south'],
       ['08/01/2021', 4, 3, 'north']], dtype=object)

现在,您可以使用上述的array来创建一个新的数据框。

注意:

如果需要 -> 通过日期列进行排序。

new_df = new_df.sort_values('Date')
输出:
         Date score score_against Region
0  01/01/2021     7             2  north
2  01/01/2021     2             7  south
1  08/01/2021     3             4  south
3  08/01/2021     4             3  north

非常感谢您!非常有帮助的简单代码,而且解释得很清楚。 - Abacus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接