python - 加速 pd.concat 的方法或使用其他方法连接表

标签 python python-3.x pandas

dfs=[]

for i in range(387):
    print(i)
    dfs.append(pd.DataFrame(0, index=range(121211), columns=range(31)))

pd.concat(dfs,axis=1) #can only change this

在上面的代码中,pd.concat非常慢,有没有办法让列连接更快?假设我只能更改 pd.concat 部分。

最佳答案

您正在实例化一个非常大的数据帧,全部包含零值。只需使用数据帧构造函数与所需的索引和列,而不是连接。

dfs = pd.DataFrame(
    0, 
    index=range(121211), 
    columns=list(range(31)) * 387
)

例如(使用更小的数据框):

>>> pd.DataFrame(0, index=range(3), columns=list(range(2)) * 3)
   0  1  0  1  0  1
0  0  0  0  0  0  0
1  0  0  0  0  0  0
2  0  0  0  0  0  0

编辑

假设每个数据帧具有相同的索引、不同的列和不同的值,请尝试直接连接 numpy 值(避免 concat 的索引和列检查的开销)。

pd.DataFrame(
    np.concatenate([df.values for df in dfs], axis=1),   
    index=dfs[0].index, 
    columns=[col for df in dfs for col in df]
)

检查此方法与 concat 的时间后,发现使用随机数据时它们非常相似。对于这么大的数据帧,您可能需要考虑替代解决方案,例如 Dask .

关于python - 加速 pd.concat 的方法或使用其他方法连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58479855/

相关文章:

python - 使用 FuncAnimation 为 Seaborn 气泡图制作动画

python - 我可以让 fabric 使用 `dzdo su -` 而不是 sudo 吗?

python - 以 block 的形式循环遍历 Pandas Dataframe

python - 如何放大箱线图?

python异步套接字编程

Python Pandas - 向量化自定义函数而不是应用

python - 在分隔符列表上编写一个循环?

python 正则表达式 "parenthesis unbalanced error"在 ubuntu 上,但不在 macos 机器上

python-3.x - Visual Studio Code Python linting 不适用于 venv 和 wsl

python-3.x - 使用 pandas.DataFrame.plot.scatter() 的 Matplotlib 警告