我試圖以一種格式壓縮我的數據,這樣它會更有用,數據格式:Table1Key AttName Rank1 Color 11 type 21 kkk 32 Color 12 type 2 如上圖所示,例如,一些鍵有 2 個屬性,而其他鍵有 3 個屬性,所以當我創建數據透視表然后嘗試標記它不起作用的列名時,hpw 我可以更改它嗎,正如上面顯示的那樣,鍵 1 有 3 個屬性名稱而 Key 2 只有 2 個導致錯誤發生最終數據:Table2Family Assortment Group Key Attribute Name Attribute Valuea ab 1 Color Greena1 ab 1 Color Yellowa2 ab 1 type shirta6 ab 1 kkkk fa3 ab 2 Color Reda4 ab 2 Type TShirta5 ab 2 Color Yellow代碼#For loop that loops over key values; key values defined as Zone AGFinals=[]Finals2=[]Finals=pd.DataFrame(Finals)Finals2=pd.DataFrame(Finals)for group in Select.groupby('Key'): # group is a tuple where the first value is the Key and the second is the dataframe Final2=group[1] Family1=Family.merge(Final2, on='Key1', how='inner') result=Family1.pivot_table(index=['Family','Assortment Group','Key'], columns='Attribute Name', values='Attribute Value', aggfunc='first').reset_index() result.columns=['Family','Assortment Group','Key','Att1','Att2','Att3'] Finals=Finals.append(result)追溯ValueError: Length mismatch: Expected axis has 5 elements, new values have 6 elements
1 回答

慕妹3242003
TA貢獻1824條經驗 獲得超6個贊
您可以使用列表理解重命名列以生成適量的 Att 列。
result.columns = ['Family','Assortment Group','Key']\ + [f'Att{i}' for i in range(1, result.shape[1]-2)]
編輯:解釋,result.shape[1]
給出結果中的列數。假設它是 5,那么前 3 個是“Family”、“Assortment Group”、“Key”。所以你想要的是再創建 2 個 Att,range(1, result.shape[1]-2)
在這種情況下range(1, 3)
,[f'Att{i}' for i in range(1, result.shape[1]-2)]
然后將迭代 i=1 和 i=2 以創建列表['Att1', 'Att2']
。將此列表添加到具有前 3 列名稱的列表中以獲得正確的列數
添加回答
舉報
0/150
提交
取消