将python数据帧转换为字典

时间:2017-10-03 23:11:02

标签: python pandas dictionary dataframe

我试图将pandas数据帧转换为字典,我目前正在获得此输出:

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

但我想要这种格式:

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

这是我的代码:

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你要找的不是字典。如果您想将收藏集存储在set中,则需要将它们存储在tuple中,因为它们可以播放。

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

或者,如果列表列表有效,那么tolist就可以了。

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