我有一個 Panda 資料框,它包含兩列以及一個默認索引。第一列是預期的“列名”,第二列是該列所需的值。
name returnattribute
0 Customer Name Customer One Name
1 Customer Code CGLOSPA
2 Customer Name Customer Two Name
3 Customer Code COTHABA
4 Customer Name Customer Three Name
5 Customer Code CGLOADS
6 Customer Name Customer Four Name
7 Customer Code CAPRCANBRA
8 Customer Name Customer Five Name
9 Customer Code COTHAMO
我想對此進行修改,以便我有 5 行兩列(“客戶名稱”和“客戶代碼”)而不是 10 行。期望的結果如下:
Customer Code Customer Name
0 CGLOSPA Customer One Name
1 COTHABA Customer Two Name
2 CGLOADS Customer Three Name
3 CAPRCANBRA Customer Four Name
4 COTHAMO Customer Five Name
我曾嘗試使用 pandas pivot 功能:
df.pivot(columns='name', values='returnattribute')
但這會導致十行仍然有備用空白:
Customer Code Customer Name
0 NaN Customer One Name
1 CGLOSPA NaN
2 NaN Customer Two Name
3 COTHABA NaN
4 NaN Customer Three Name
5 CGLOADS NaN
6 NaN Customer Four Name
7 CAPRCANBRA NaN
8 NaN Customer Five Name
9 COTHAMO NaN
如何旋轉資料框以僅獲得 5 行兩列?
uj5u.com熱心網友回復:
在不傳遞引數df.pivot時使用默認值。因此,輸出。indexdf.index
- 從檔案
DataFrame.pivot:
index: str 或 object 或 str 串列,可選
- 用于制作新框架索引的列。如果
None,使用現有索引。
獲得所需的輸出。您必須創建一個新的索引列,如下所示。
df.assign(idx=df.index // 2).pivot(
index="idx", columns="name", values="returnattribute"
)
# name Customer Code Customer Name
# idx
# 0 CGLOSPA Customer One Name
# 1 COTHABA Customer Two Name
# 2 CGLOADS Customer Three Name
# 3 CAPRCANBRA Customer Four Name
# 4 COTHAMO Customer Five Name
因為每兩行代表一個資料點。您可以reshape獲取資料并構建所需的資料框。
reshaped = df['returnattribute'].to_numpy().reshape(-1, 2)
# array([['Customer One Name', 'CGLOSPA'],
# ['Customer Two Name', 'COTHABA'],
# ['Customer Three Name', 'CGLOADS'],
# ['Customer Four Name', 'CAPRCANBRA'],
# ['Customer Five Name', 'COTHAMO']], dtype=object)
col_names = pd.unique(df.name)
# array(['Customer Name', 'Customer Code'], dtype=object)
out = pd.DataFrame(reshaped, columns=col_names)
# Customer Name Customer Code
# 0 Customer One Name CGLOSPA
# 1 Customer Two Name COTHABA
# 2 Customer Three Name CGLOADS
# 3 Customer Four Name CAPRCANBRA
# 4 Customer Five Name COTHAMO
# we can reorder the columns using reindex.
uj5u.com熱心網友回復:
您也可以將新索引直接傳遞給pivot_table,aggfunc='first'因為您有非數字資料:
df.pivot_table(index=df.index//2, columns='name',
values='returnattribute', aggfunc='first')
輸出:
name Customer Code Customer Name
0 CGLOSPA Customer One Name
1 COTHABA Customer Two Name
2 CGLOADS Customer Three Name
3 CAPRCANBRA Customer Four Name
4 COTHAMO Customer Five Name
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/406628.html
標籤:
