简体   繁体   中英

Create column of dictionaries with keys and values from other two columns in Pandas DataFrame

I currently have a Pandas DataFrame where there are two columns that each contain lists and another column that contains the tuple pairs of the elements of those two lists. A toy example for the sake of convenience would be something like:

        col1       col2       col3       col4
0        'a'       [0, 1]     [8, 9]     [(0, 8), (1, 9)]
1        'b'       [2, 3]     [10, 11]   [(2, 10), (3, 11)]
2        'c'       [4, 5]     [12, 13]   [(4, 12), (5, 13)]
3        'd'       [6, 7]     [14, 15]   [(6, 14), (7, 15)]

What I want to do is to create a 5th column col5 that contains dictionaries with the values from col3 as keys and the values from col2 as values. For example:

        col1       col2       col3       col4                 col5
0        'a'       [0, 1]     [8, 9]     [(0, 8), (1, 9)]     {'8': 0, '9': 1}
1        'b'       [2, 3]     [10, 11]   [(2, 10), (3, 11)]   {'10': 2, '11': 3}
2        'c'       [4, 5]     [12, 13]   [(4, 12), (5, 13)]   {'12': 4, '13': 5}
3        'd'       [6, 7]     [14, 15]   [(6, 14), (7, 15)]   {'14': 6, '15': 7}

I've tried methods such as

df['col5'] = dict(zip(df['col4'].apply(ast.literal_eval), df['col3'].apply(ast.literal_eval)))

but I receive an error. What would be the most appropriate way that I go about this? Thanks in advance.

If laready created col4 is possible loop with map :

df['col5'] = df['col4'].map(lambda x: [{b:a} for a, b in ast.literal_eval(x)])
print (df)
  col1    col2      col3                col4                col5
0  'a'  [0, 1]    [8, 9]    [(0, 8), (1, 9)]    [{8: 0}, {9: 1}]
1  'b'  [2, 3]  [10, 11]  [(2, 10), (3, 11)]  [{10: 2}, {11: 3}]
2  'c'  [4, 5]  [12, 13]  [(4, 12), (5, 13)]  [{12: 4}, {13: 5}]
3  'd'  [6, 7]  [14, 15]  [(6, 14), (7, 15)]  [{14: 6}, {15: 7}]

Or if inputs are col3 and col2 use zip with list comprehension :

df['col5'] = [dict(zip(ast.literal_eval(a), ast.literal_eval(b))) 
              for a, b in zip(df['col3'], df['col2'])]

print (df)
  col1    col2      col3                col4            col5
0  'a'  [0, 1]    [8, 9]    [(0, 8), (1, 9)]    {8: 0, 9: 1}
1  'b'  [2, 3]  [10, 11]  [(2, 10), (3, 11)]  {10: 2, 11: 3}
2  'c'  [4, 5]  [12, 13]  [(4, 12), (5, 13)]  {12: 4, 13: 5}
3  'd'  [6, 7]  [14, 15]  [(6, 14), (7, 15)]  {14: 6, 15: 7}

Or solution with apply :

df['col5'] = (df.apply(lambda x:  dict(zip(ast.literal_eval(x['col3']), 
                                           ast.literal_eval(x['col2']))), axis=1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM