user308827
user308827

Reputation: 21971

Convert pandas dataframe with column containing list of dictionaries to tuple of tuples

colA    colB    colC
-36.10342651    -62.17990636    [{lat:-36.10342650837965,lng:-62.179906361743},{lat:-36.108743958442865,lng:-62.17361161411073},{lat:-36.1167965139411,lng:-62.18381673356545},{lat:-36.11159519706228,lng:-62.19034991799284}]
-36.10342651    -62.17990636    [{lat:-36.10342650837965,lng:-62.179906361743},{lat:-36.108743958442865,lng:-62.17361161411073},{lat:-36.1167965139411,lng:-62.18381673356545},{lat:-36.11159519706228,lng:-62.19034991799284}]
-36.10342651    -62.17990636    [{lat:-36.10342650837965,lng:-62.179906361743},{lat:-36.108743958442865,lng:-62.17361161411073},{lat:-36.1167965139411,lng:-62.18381673356545},{lat:-36.11159519706228,lng:-62.19034991799284}]

I want to convert each row in colC in the dataframe above into this: ((-36.10342650837965 -62.179906361743,-36.108743958442865 -62.17361161411073,-36.1167965139411 -62.18381673356545,-36.11159519706228 -62.19034991799284))

I can convert a list of dictionary to tuple doing something like this, but it does not get the right output:

dict_list = [(key, )+tuple(val) for dic in ini_list  
                       for key, val in dic.items()] 

Upvotes: 0

Views: 59

Answers (1)

Henry Yik
Henry Yik

Reputation: 22503

You can use list comprehension with chain.from_iterable:

from itertools import chain

df["new"] = [(tuple(chain.from_iterable(s.values() for s in i)),) for i in df["colC"]]

print (df)

        colA       colB                                               colC                                                new
0 -36.103427 -62.179906  [{'lat': -36.10342650837965, 'lng': -62.179906...  ((-36.10342650837965, -62.179906361743, -36.10...
1 -36.103427 -62.179906  [{'lat': -36.10342650837965, 'lng': -62.179906...  ((-36.10342650837965, -62.179906361743, -36.10...
2 -36.103427 -62.179906  [{'lat': -36.10342650837965, 'lng': -62.179906...  ((-36.10342650837965, -62.179906361743, -36.10...

Upvotes: 2

Related Questions