Python 使用新键将数据帧转换为Dict格式

Python 使用新键将数据帧转换为Dict格式,python,json,dictionary,pandas,Python,Json,Dictionary,Pandas,转换此项的最佳方法是什么: deviceid devicetype 0 b569dcb7-4498-4cb4-81be-333a7f89e65f Google 1 04d3b752-f7a1-42ae-8e8a-9322cda4fd7f Android 2 cf7391c5-a82f-4889-8d9e-0a423f132026 Android 为此: 0 {"deviceid":"b569dcb7-449

转换此项的最佳方法是什么:

                               deviceid devicetype
0  b569dcb7-4498-4cb4-81be-333a7f89e65f     Google
1  04d3b752-f7a1-42ae-8e8a-9322cda4fd7f    Android
2  cf7391c5-a82f-4889-8d9e-0a423f132026    Android
为此:

0 {"deviceid":"b569dcb7-4498-4cb4-81be-333a7f89e65f","devicetype":["Google"]}
1 {"deviceid":"04d3b752-f7a1-42ae-8e8a-9322cda4fd7f","devicetype":["Android"]}
2 {"deviceid":"cf7391c5-a82f-4889-8d9e-0a423f132026","devicetype":["Android"]}
我已经尝试过df.to_dict(),但这只会给出:

{'deviceid': {0: 'b569dcb7-4498-4cb4-81be-333a7f89e65f',
  1: '04d3b752-f7a1-42ae-8e8a-9322cda4fd7f',
  2: 'cf7391c5-a82f-4889-8d9e-0a423f132026'},
 'devicetype': {0: 'Google', 1: 'Android', 2: 'Android'}}

您可以使用apply with
来应用json

In [11]: s = df.apply((lambda x: x.to_json()), axis=1)

In [12]: s[0]
Out[12]: '{"deviceid":"b569dcb7-4498-4cb4-81be-333a7f89e65f","devicetype":"Google"}'
要获取设备类型的列表,可以手动执行以下操作:

In [13]: s1 = df.apply((lambda x: {"deviceid": x["deviceid"], "devicetype": [x["devicetype"]]}), axis=1)

In [14]: s1[0]
Out[14]: {'deviceid': 'b569dcb7-4498-4cb4-81be-333a7f89e65f', 'devicetype': ['Google']}

要扩展上一个答案,
To_dict()
应该比
To_json()

对于较大的测试数据帧,这似乎是正确的,但是对于您提供的示例来说,
to_dict()
方法实际上稍微慢一点

大型测试集

In [1]: %timeit s = df.apply((lambda x: x.to_json()), axis=1)
Out[1]: 100 loops, best of 3: 5.88 ms per loop

In [2]: %timeit s = df.apply((lambda x: x.to_dict()), axis=1)
Out[2]: 100 loops, best of 3: 3.91 ms per loop
提供的示例

In [3]: %timeit s = df.apply((lambda x: x.to_json()), axis=1)
Out[3]: 1000 loops, best of 3: 375 µs per loop

In [4]: %timeit s = df.apply((lambda x: x.to_dict()), axis=1)
Out[4]: 1000 loops, best of 3: 450 µs per loop

这是因为在创建json的过程中,to_json创建了一个dict,即基本上to_json做str(x.to_dict())。也就是说,dict是另一个很好的选项+1。