将数据帧转换为dict,将列作为键内键

时间:2016-06-22 06:00:24

标签: python python-2.7 dictionary pandas dataframe

我有一个熊猫数据框。

         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'作为键中的子键,而该列中的值作为子键内的值。所以,前两行的输出就像。

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设置为键,但是这些值被添加为键内的列表,而不是键内的键。

1 个答案:

答案 0 :(得分:2)

您可以使用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'}}