gpt4 book ai didi

python - 在将列与 Python Pandas 结合的同时 reshape (融化?)数据

转载 作者:行者123 更新时间:2023-12-04 01:02:13 24 4
gpt4 key购买 nike

我有以下数据框:

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
我怎样才能最好地 reshape 它以将 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
非常感谢

最佳答案

您可以获取内部 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

关于python - 在将列与 Python Pandas 结合的同时 reshape (融化?)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67886244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com