具有键和值列表的列到具有字典列表的列

时间:2019-06-07 16:01:53

标签: python python-3.x pandas

我在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}]

最有效的方法是什么?

1 个答案:

答案 0 :(得分:1)

我同意cs95

这太恶心了...

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}]