[英]How to select columns from MultiIndex pandas table in a custom order?
如何以自定義順序從 MultiIndex pandas 表中的 select 列? 在這種情況下,我怎樣才能讓數量出現在價格之前(不使用升序 = false)以及要按順序排列的大小:中、大、小。
所需的 output:
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
Dataframe的創建:
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'])]
您可以使用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
傳遞列表列表有效:
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
pandas 1.2版
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.