簡體   English   中英

重塑(融化?)數據,同時將列與 Python Pandas

[英]Reshape (Melt?) data whilst combining columns with Python Pandas

我有以下 dataframe:

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 堆疊在一起? 所需的 output 如下所示:

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'])

OUTPUT:

         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創建一個新的 dataframe。

筆記:

如果需要 -> 按日期列排序。

new_df = new_df.sort_values('Date')
OUTPUT:
         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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM