如何以自定義順序從 MultiIndex pandas 表中選擇列?在這種情況下,我如何讓數量先于價格(不使用升序 = false)以及大小的順序:中、大、小。
期望的輸出:
Quantity Price
Size medium large small medium large small
0 3 4 3 6 6 5
1 6 7 5 9 9 8
2 2 2 1 4 5 2
資料框的創建:
df = pd.DataFrame({"Item": ["foo", "foo", "foo", "bar", "bar",
"bar", "baz", "baz", "baz"],
"Size": ["small", "medium", "large", "small",
"medium", "large", "small", "medium",
"large"],
"Price": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"Quantity": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
df = pd.pivot_table(df,index=["Item"],columns=["Size"],values=["Price","Quantity"],aggfunc=np.sum)
df.reset_index(drop=True, inplace=True)
#Dataframe:
Price Quantity
Size large medium small large medium small
0 4 3 3 6 6 5
1 7 6 5 9 9 8
2 2 2 1 5 4 2
我曾嘗試使用 dataframe.loc[],但是,我意識到 .loc[] 不維護特定順序。
df.loc[:, (['Quantity', 'Price'], ['medium', 'large', 'small'])]
uj5u.com熱心網友回復:
您可以使用pd.MultiIndex.from_product來生成索引:
idx = pd.MultiIndex.from_product([['Quantity', 'Price'], ['medium', 'large', 'small']])
idx
MultiIndex([('Quantity', 'medium'),
('Quantity', 'large'),
('Quantity', 'small'),
( 'Price', 'medium'),
( 'Price', 'large'),
( 'Price', 'small')],
)
df[idx]
Quantity Price
Size medium large small medium large small
0 6 6 5 3 4 3
1 9 9 8 6 7 5
2 4 5 2 2 2 1
uj5u.com熱心網友回復:
傳遞串列串列有效:
df.loc(axis=1)[['Quantity', 'Price'], ['medium', 'large', 'small']]
Quantity Price
Size medium large small medium large small
0 6 6 5 3 4 3
1 9 9 8 6 7 5
2 4 5 2 2 2 1
大熊貓版本 1.2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/399109.html
下一篇:或者將值分配給兩列
