【问题标题】:Transform a python dataframe into a dictionary将 python 数据框转换为字典
【发布时间】:2017-10-03 23:11:01
【问题描述】:

我正在尝试将 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()

我该如何解决这个问题?

【问题讨论】:

  • {{'store_a','BRAZIL', 'STORE_A'}, {'store_b','BRAZIL', 'STORE_B'}} 不是字典。

标签: python pandas dictionary dataframe


【解决方案1】:

您要查找的不是字典。如果您想将集合存储在 set 中,则需要将它们存储在 tuples 中,因为它们是可散列的。

>>> 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']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2022-07-05
    • 2019-10-19
    • 2016-10-12
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多