1

Suppose we have one data frame df

 id=['abc','xyz','lmn']
 df=pd.DataFrame(id)
 df.columns=['id']
 print(df)

     id
 0  abc
 1  xyz
 2  lmn

I want to generate the following array from it

 idd=[ { 'id': 'abc' ,},
       {'id': 'xyz',},
        {'id':'lmn' ,},]

How can I do it?

1 Answer 1

3

You could use method to_dict with records:

In [61]: df
Out[61]:
    id
0  abc
1  xyz
2  lmn

In [62]: df.to_dict('records')
Out[62]: [{'id': 'abc'}, {'id': 'xyz'}, {'id': 'lmn'}]

Edit

It seems that docs lack information about keywords for to_dict method but you could get it from console:

Help on method to_dict in module pandas.core.frame:

to_dict(orient='dict') method of pandas.core.frame.DataFrame instance Convert DataFrame to dictionary.

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

      .. versionadded:: 0.17.0

    Abbreviations are allowed. `s` indicates `series` and `sp`
    indicates `split`.

Returns
-------
result : dict like {column -> {index -> value}}
Sign up to request clarification or add additional context in comments.

1 Comment

If you need JSON, you can also use df.to_json(orient = 'records') or after importing the json library, json.dumps(df.to_dict('records')). pandas.pydata.org/pandas-docs/stable/generated/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.