我在pandas
中有这个东西:
Key Level Subkeys Values
0 A 0 [A1, A2] [3, 4]
1 B 1 [B1] [2]
2 C 2 [C1, C2, C3] [8, 5, 1]
我想将其转换为此:
Key Level Subdicts
0 A 0 [{A1: 3, {A2: 4}]
1 B 1 [{B1: 2]
2 C 2 [{C1: 8}, {C2: 5}, {C3: 1}]
最有效的方法是什么?
答案 0 :(得分:1)
这太恶心了...
df.assign(Subdicts=[[{x: y} for x, y in zip(X, Y)] for X, Y in zip(df.Subkeys, df.Values)])
Key Level Subkeys Values Subdicts
0 A 0 [A1, A2] [3, 4] [{'A1': 3}, {'A2': 4}]
1 B 1 [B1] [2] [{'B1': 2}]
2 C 2 [C1, C2, C3] [8, 5, 1] [{'C1': 8}, {'C2': 5}, {'C3': 1}]