Home > Software engineering >  How to create a list with column name for each row of a df
How to create a list with column name for each row of a df

Time:11-20

i have this df:

have

and i want to make a list with the column name and data for each row who looks like this:

[{'userid': '1', 'account_holder': 'Vince', 'broker': '1090', 'account_id': '807521'}, {'userid': '2', 'account_holder': 'Joana', 'broker': '3055', 'account_id': '272167'}, {'userid': '3', 'account_holder': 'Dominique', 'broker': '5143', 'account_id': '37009'}, {'userid': '4', 'account_holder': 'James', 'broker': '5522', 'account_id': '905527'}]

can you help me?

i'm new at python and searched for info but not finding anything about it

CodePudding user response:

We can use your expected output to create a dataframe

>>> import pandas as pd
>>> df = pd.DataFrame([{'userid': '1', 'account_holder': 'Vince', 'broker': '1090', 'account_id': '807521'}, {'userid': '2', 'account_holder': 'Joana', 'broker': '3055', 'account_id': '272167'}, {'userid': '3', 'account_holder': 'Dominique', 'broker': '5143', 'account_id': '37009'}, {'userid': '4', 'account_holder': 'James', 'broker': '5522', 'account_id': '905527'}])
>>> df
  userid account_holder broker account_id
0      1          Vince   1090     807521
1      2          Joana   3055     272167
2      3      Dominique   5143      37009
3      4          James   5522     905527

DataFrame has a to_dict method that can output in multiple ways. help(pd.DataFrame.to_dict) says

orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
    Determines the type of the values of the dictionary.

    - 'dict' (default) : dict like {column -> {index -> value}}
    - 'list' : dict like {column -> [values]}
    - 'series' : dict like {column -> Series(values)}
    - 'split' : dict like
      {'index' -> [index], 'columns' -> [columns], 'data' -> [values]}
    - 'records' : list like
      [{column -> value}, ... , {column -> value}]
    - 'index' : dict like {index -> {column -> value}}

You can call to_dict with "records" orientation to get the result you want

>>> df.to_dict("records")
[{'userid': '1', 'account_holder': 'Vince', 'broker': '1090', 'account_id': '807521'}, {'userid': '2', 'account_holder': 'Joana', 'broker': '3055', 'account_id': '272167'}, {'userid': '3', 'account_holder': 'Dominique', 'broker': '5143', 'account_id': '37009'}, {'userid': '4', 'account_holder': 'James', 'broker': '5522', 'account_id': '905527'}]
  • Related