2
給出一個數據幀,看起來像:棧上面列在大熊貓透視表中值標籤
import numpy as np
import pandas as pd
df = pd.DataFrame({
'Key1': ['one', 'one', 'two', 'three'] * 3,
'Key2': ['A', 'B', 'C'] * 4,
'Value1': np.random.randn(12),
'Value2': np.random.randn(12)
})
print df
Key1 Key2 Value1 Value2 0 one A 1.405817 1.307511 1 one B -0.037627 -0.215800 2 two C -0.116591 -1.195066 3 three A 2.044775 -1.207433 4 one B -1.109636 0.031521 5 one C -1.529597 1.761366 6 two A -1.349865 0.321454 7 three B 0.814374 2.285579 8 one C 0.178702 0.479210 9 one A 0.718921 0.504311 10 two B -0.375898 -0.379315 11 three C -0.822250 0.703811
我可以轉動它,這樣我得到的第一個鍵爲行和第二鍵列
pt = df.pivot_table(
index=['Key1'],
columns=['Key2'],
values=['Value1','Value2']
)
print pt
Value1 Value2 Key2 A B C A B C Key1 one -0.076303 -0.899175 0.631831 -1.196249 0.339583 0.583173 three 0.105773 0.460911 -0.387941 0.697660 1.091828 1.447365 two 1.391854 0.499841 -0.422887 -0.366169 -0.230001 2.417211
如何翻轉,使得值和列由列堆疊的第一和隨後的值,例如我看過MultiIndexes但我看不出這會如何影響佈局。