2015-11-13 75 views
1

什么是将此转换的最佳方式:熊猫据帧到快译通格式与新的密钥

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

回答

2

您可以使用应用与to_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']} 
1

为了扩大对以前的答案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 
+0

这是因为创建一个JSON的方式,to_json创建一个字典,即。基本上to_json是str(x.to_dict())。这就是说to_dict是另一个不错的选择+1。 –