Skip to main content
 首页 » 编程设计

python之优化 pandas dataframe 到 json 的成本

2024年12月31日9lhb25

我的目标是按 1 列对数据框进行排序,并尽可能高效地返回一个 json 对象。

为了复制,请定义以下数据框:

import pandas as pd 
import numpy as np 
test = pd.DataFrame(data={'a':[np.random.randint(0,100) for i in range(10000)], 'b':[i + np.random.randint(0,100) for i in range(10000)]}) 
 
       a      b 
0     74     89 
1     55     52 
2     53     39 
3     26     21 
4     69     34 

我需要做的是按 a 列排序,然后将输出编码为 json 对象。我正在采用基本方法并执行以下操作:

test.sort_values('a', ascending=True, inplace=True) # n log n 
data = [{}] # 1 
for d in test.itertuples(): # n times 
    to_append = {'id': d.Index, 'data': {'a': d.a, 'b': d.b}} # 3  
    data.append(to_append) # 1 

那么成本是nlogn + n*4?有没有更有效的方法呢?

请您参考如下方法:

我注意到 pandas 读取和写入 JSON 的速度比纯 python 慢。如果您确定只有两列,您可以这样做:

data = [{'id' : x, 'data' : {'a' : y, 'b' : z}}  
            for x, (y, z) in zip(test.index, test.values.tolist())]  
json.dumps(data) 

如果你有更多的列需要担心,你可以这样做:

c = test.columns 
data = [{'id' : x, 'data' : dict(zip(c, y))}  
            for x, *y in zip(test.index, test.values.tolist())] 
json.dumps(data) 

或者,如果您可以处理它,请在保存前调用 reset_index:

c = test.columns 
data = [{'id' : x[0], 'data' : dict(zip(c, x[1:]))}  
            for x in test.reset_index().values.tolist()] 
json.dumps(data)