【问题标题】:Converting Data frame into a dict with columns as key inside key将数据框转换为以列作为键内键的字典
【发布时间】:2016-10-23 21:43:20
【问题描述】:

我有一个熊猫数据框。

         mac_address  no. of co_visit    no. of random_visit
0  00:02:1a:11:b0:b9                1                      2
1  00:02:71:d6:04:84                1                      1
2  00:05:33:34:2f:f2                1                      3
3  00:08:22:04:c4:fb                1                      4
4  00:08:22:06:7b:41                1                      1
5  00:08:22:07:48:15                1                      1
6  00:08:22:08:a8:54                1                      3
7  00:08:22:0e:0a:fc                1                      1

我想将它转换为一个字典,其中 mac_address 作为键,'no. of co_visit''no. of random_visit' 作为键内的子键,跨该列的值作为子键内的值。所以,我前 2 行的输出将是这样的。

00:02:1a:11:b0:b9:{no. of co_visit:1, no. of random_visit: 2}
00:02:71:d6:04:84:{no. of co_visit:1, no. of random_visit: 1}

我正在使用 python2.7。谢谢。

我能够将 mac_address 设置为键,但值被添加为键内的列表,而不是键内的键。

【问题讨论】:

  • Stackoverflow 社区不会接受在没有任何证据表明已投入努力的情况下寻求帮助的问题。除非您向我们展示您到目前为止所做的尝试以及您遇到的问题,否则这个问题可能会被关闭。
  • 好吧@SuperSaiyan 我曾经发布过整个问题,后来版主建议我问你卡在哪里。所以这是我无法弄清楚的一个步骤。
  • 提及你卡在哪里总是很棒的。您还需要包括解决问题的努力——我们中的许多人都会很乐意为您提供帮助..

标签: python python-2.7 dictionary pandas dataframe


【解决方案1】:

您可以使用pandas.DataFrame.Tto_dict()

df.set_index('mac_address').T.to_dict()

输出:

{'00:02:1a:11:b0:b9': {'no. of co_visit': '1', 'no. of random_visit': '2'},
 '00:02:71:d6:04:84': {'no. of co_visit': '1', 'no. of random_visit': '1'},
 '00:05:33:34:2f:f2': {'no. of co_visit': '1', 'no. of random_visit': '3'},
 '00:08:22:04:c4:fb': {'no. of co_visit': '1', 'no. of random_visit': '4'},
 '00:08:22:06:7b:41': {'no. of co_visit': '1', 'no. of random_visit': '1'},
 '00:08:22:07:48:15': {'no. of co_visit': '1', 'no. of random_visit': '1'},
 '00:08:22:08:a8:54': {'no. of co_visit': '1', 'no. of random_visit': '3'},
 '00:08:22:0e:0a:fc': {'no. of co_visit': '1', 'no. of random_visit': '1'}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2021-10-31
    • 2021-10-13
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2022-08-21
    相关资源
    最近更新 更多