Advertisement
furas

Python - Pandas - split dictionary into columns

Nov 6th, 2021
639
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. import pandas as pd
  2.  
  3. data = [
  4.    [123, [{'type': 'Name', 'value': 'A'}, {'type': 'Birthdate', 'value': '1991'}, {'type': 'Style', 'value': 'C'}]],
  5.    [128, [{'type': 'Birthdate', 'value': '1994'}, {'type': 'Name', 'value': 'F'}, {'type': 'Colour', 'value': 'Z'}]],
  6. ]
  7.  
  8. df = pd.DataFrame(data, columns=['pin', 'attributes'])
  9. print(df)
  10.  
  11. # --- functions ---
  12.  
  13. def convert(row):
  14.     result = pd.Series(dtype=object)
  15.  
  16.     for item in row:
  17.         key = item['type']
  18.         val = item['value']
  19.         result[key] = val
  20.        
  21.     return result
  22.  
  23. # --- main ---
  24.  
  25. new_columns = df['attributes'].apply(convert)
  26. df = df.join(new_columns)
  27.  
  28. df = df.drop(columns=['attributes'])
  29.  
  30. print(df)
  31.  
  32. """
  33. Result:
  34.  
  35.   pin                                         attributes
  36. 0  123  [{'type': 'Name', 'value': 'A'}, {'type': 'Bir...
  37. 1  128  [{'type': 'Birthdate', 'value': '1994'}, {'typ...
  38.  
  39.   pin Name Birthdate Style Colour
  40. 0  123    A      1991     C    NaN
  41. 1  128    F      1994   NaN      Z
  42. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement