将 pandas 数据帧的成本优化为 json
Optimising the cost of pandas dataframe to json
我的目标是尽可能高效地按 1 列和 return 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)
我的目标是尽可能高效地按 1 列和 return 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)