简体   繁体   中英

Transform a python dataframe into a dictionary

I'm trying to transform a pandas dataframe into a dictionary, I'm currently getting this output:

{'country': {0: 'BRAZIL', 1: 'BRAZIL'}, 'store_nick': {0: 'store_a', 1: 'store_b'}, 'store': {0: 'STORE_A', 1: 'STORE_B'}}

But I want this format:

{{'store_a','BRAZIL', 'STORE_A'}, {'store_b','BRAZIL', 'STORE_B'}}

This is my code:

dimensions[['fieldA','fieldB','fieldC']].to_dict()

How can I fix this?

What you're looking for is not a dictionary. If you want to store collections in a set , you'll need to store them in tuple s, since they are hashable.

>>> set(df.apply(tuple, 1).values)
{('BRAZIL', 'STORE_A', 'store_a'), ('BRAZIL', 'STORE_B', 'store_b')}

Alternatively, if a list of lists works, then tolist is the way to go.

>>> df.values.tolist()
[['BRAZIL', 'STORE_A', 'store_a'], ['BRAZIL', 'STORE_B', 'store_b']]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM