BUG: df.setitem can be 10x slower than pd.concat(..., axis=1) (original) (raw)


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

import pandas as pd, numpy as np from string import ascii_lowercase

def setitem(x, x_cols, df): new = pd.DataFrame(index=df.index) new[x_cols] = x new[df.columns] = df return new

def concat(x, x_cols, df): return pd.concat( [ pd.DataFrame(x, columns=x_cols, index=df.index), df, ], axis=1, )

x = np.ones((1000, 10)) x_col = list(ascii_lowercase[:10]) df = pd.DataFrame( { "str": np.random.choice(np.array(list(ascii_lowercase)), size=1000), "int": np.arange(1000, dtype=int), } )

%timeit setitem(x, x_col, df)

3.78 ms ± 193 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit concat(x, x_col, df)

306 µs ± 9.29 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Problem description

This seems unintuitive from a performance perspective. I would assume that these would be close to equivalent. The setitem implementation might even be expected to have better performance due to less allocation.

While this is a stripped down example, the use case is building a dataframe to return from a function. Making a dataframe, then adding columns seemed like the natural idiom here.

Output of pd.show_versions()

Details

INSTALLED VERSIONS
------------------
commit           : 67a3d4241ab84419856b84fc3ebc9abcbe66c6b3
python           : 3.8.5.final.0
python-bits      : 64
OS               : Darwin
OS-release       : 19.6.0
Version          : Darwin Kernel Version 19.6.0: Thu Oct 29 22:56:45 PDT 2020; root:xnu-6153.141.2.2~1/RELEASE_X86_64
machine          : x86_64
processor        : i386
byteorder        : little
LC_ALL           : None
LANG             : en_US.UTF-8
LOCALE           : en_US.UTF-8

pandas           : 1.1.4
numpy            : 1.19.4
pytz             : 2020.1
dateutil         : 2.8.1
pip              : 20.2.4
setuptools       : 50.3.2
Cython           : 0.29.21
pytest           : 6.1.2
hypothesis       : None
sphinx           : 3.2.1
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : 2.11.2
IPython          : 7.19.0
pandas_datareader: None
bs4              : None
bottleneck       : None
fsspec           : 0.8.4
fastparquet      : None
gcsfs            : None
matplotlib       : 3.3.3
numexpr          : 2.7.1
odfpy            : None
openpyxl         : None
pandas_gbq       : None
pyarrow          : 2.0.0
pytables         : None
pyxlsb           : None
s3fs             : None
scipy            : 1.5.4
sqlalchemy       : 1.3.18
tables           : 3.6.1
tabulate         : 0.8.7
xarray           : 0.16.1
xlrd             : 1.2.0
xlwt             : None
numba            : 0.51.2