如何排列 Pandas 資料透視表的列?
例如,對于樞軸輸出,我如何交換 D 和 E 頭寸以及如何交換大頭寸和小頭寸?
編輯:我正在尋找一種解決方案,該解決方案允許自定義訂單適用于其他實體
#Sample Dataframe
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two",
"one", "one", "two", "two"],
"C": ["small", "large", "large", "small",
"small", "large", "small", "small",
"large"],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
#Dataframe:
A B C D E
0 foo one small 1 2
1 foo one large 2 4
2 foo one large 2 5
3 foo two small 3 5
4 foo two small 3 6
5 bar one large 4 6
6 bar one small 5 8
7 bar two small 6 9
8 bar two large 7 9
#Code used to pivot
display(pd.pivot_table(df,index=['A','B'],columns=['C'],values=['D','E'],aggfunc=np.sum))
Pivot table output:
D E
C large small large small
A B
bar one 4.0 5.0 6.0 8.0
two 7.0 6.0 9.0 9.0
foo one 4.0 1.0 9.0 2.0
two NaN 6.0 NaN 11.0
uj5u.com熱心網友回復:
你可以自己定義codes一個MultiIndex實體的屬性(比如一個ordered CategoricalIndex)
out.columns = out.columns.set_codes([
out.columns.get_level_values(0).map({'E': 0, 'D': 1}),
out.columns.get_level_values(1).map({'small': 0, 'large': 1})
])
print(out)
# Output
D E
C small large small large
A B
bar one 4.0 5.0 6.0 8.0
two 7.0 6.0 9.0 9.0
foo one 4.0 1.0 9.0 2.0
two NaN 6.0 NaN 11.0
您可以為月份定義自定義映射,如下所示:
import calendar
month_codes = dict(enumerate(calendar.month_abbr[1:]))
print(month_codes)
# Output
{0: 'Jan', 1: 'Feb', 2: 'Mar', 3: 'Apr', 4: 'May', 5: 'Jun',
6: 'Jul', 7: 'Aug', 8: 'Sep', 9: 'Oct', 10: 'Nov', 11: 'Dec'}
uj5u.com熱心網友回復:
這是您想要做的嗎?
pivot1 = pd.pivot_table(df,index=['A','B'],columns=['C'], values=['D','E'],aggfunc=np.sum)
pivot2 = pivot1[[('E', 'small'),
('E', 'large'),
('D', 'small'),
('D', 'large')]]

uj5u.com熱心網友回復:
您可以在此示例中使用sort_indexwith ascending=False:
df.sort_index(1, ascending=False)
輸出
E D
C small large small large
A B
bar one 8.0 6.0 5.0 4.0
two 9.0 9.0 6.0 7.0
foo one 2.0 9.0 1.0 4.0
two 11.0 NaN 6.0 NaN
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/398828.html
