Pandas: convert data columns to dict with header col as dict key and col values as dict values
I have a dataframe that looks like this:
NAME ID
155 ARBITRARY_A 697381
208 ARBITRARY_B 691820
265 ARBITRARY_C 691782
272 ARBITRARY_D 695593
I want to convert it to a list of dictionaries that looks like this:
[{name:ARBITRARY_A, id:697381}, {name:ARBITRARY_B, id:691820},
{name:ARBITRARY_C, id:691782}, {name:ARBITRARY_D, id:695593}]
What is the fastest / best way to accomplish this operation?
+3
source to share
3 answers
As pointed out in the comments, pandas.DataFrame.to_dict()
one can use. And in your case you need orient
like record
:
Code:
df.to_dict('record')
Test code:
df = pd.read_fwf(StringIO(u"""
NAME ID
155 ARBITRARY_A 697381
208 ARBITRARY_B 691820
265 ARBITRARY_C 691782
272 ARBITRARY_D 695593"""),
header=1, index_col=0)
print(df)
print(df.to_dict('record'))
Results:
NAME ID
155 ARBITRARY_A 697381
208 ARBITRARY_B 691820
265 ARBITRARY_C 691782
272 ARBITRARY_D 695593
[{u'NAME': u'ARBITRARY_A', u'ID': 697381L}, {u'NAME': u'ARBITRARY_B', u'ID': 691820L}, {u'NAME': u'ARBITRARY_C', u'ID': 691782L}, {u'NAME': u'ARBITRARY_D', u'ID': 695593L}]
+4
source to share
You can squeeze a little more performance out of it by making your own considerations.
v = df.values.tolist()
c = df.columns.values.tolist()
[dict(zip(c, x)) for x in v]
[{'ID': 697381L, 'NAME': 'ARBITRARY_A'},
{'ID': 691820L, 'NAME': 'ARBITRARY_B'},
{'ID': 691782L, 'NAME': 'ARBITRARY_C'},
{'ID': 695593L, 'NAME': 'ARBITRARY_D'}]
+3
source to share