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?
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}}
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.