我有以下數據結構:拼合在多指標大熊貓數據幀一一對一映射
from collections import OrderedDict
import pandas as pd
d = OrderedDict([
((5, 3, 1), {'y1': 1}),
((5, 3, 2), {'y2': 2}),
((5, 4, 1), {'y1': 10}),
((5, 4, 2), {'y2': 20}),
((6, 3, 1), {'y1': 100}),
((6, 3, 2), {'y2': 200}),
((6, 4, 1), {'y1': 1000}),
((6, 4, 2), {'y2': 2000}),
])
df = pd.DataFrame(
d.values(),
index=pd.MultiIndex.from_tuples(d.keys(), names=['x3', 'x2', 'x1']),
)
表看起來像
y1 y2
x3 x2 x1
5 3 1 1 NaN
2 NaN 2
4 1 10 NaN
2 NaN 20
6 3 1 100 NaN
2 NaN 200
4 1 1000 NaN
2 NaN 2000
正如你可以看到有一個單對一的x1和列之間的映射(X1 = 1:Y1,X1 = 2:Y2),我想變平成爲
y1 y2
x3 x2
5 3 1 2
4 10 20
6 3 100 200
4 1000 2000
如何做呢?
編輯:或者反過來:
y
x3 x2 x1
5 3 1 1
2 2
4 1 10
2 20
6 3 1 100
2 200
4 1 1000
2 2000
你嘗試過這麼遠嗎? – Roman