NumPy 方式
这是使用 advanced indexing 的矢量化 NumPy 方式 -
# Extract array data
In [10]: a = df.values
# Get integer based column IDs
In [11]: col_idx = np.searchsorted(df.columns, columns_to_select)
# Use NumPy's advanced indexing to extract relevant elem per row
In [12]: a[np.arange(len(col_idx)), col_idx]
Out[12]: array([ 10, 2, 3, 400])
如果df的列名没有排序,我们需要使用sorter参数和np.searchsorted。为这样的通用 df 提取 col_idx 的代码将是:
# https://stackoverflow.com/a/38489403/ @Divakar
def column_index(df, query_cols):
cols = df.columns.values
sidx = np.argsort(cols)
return sidx[np.searchsorted(cols,query_cols,sorter=sidx)]
所以,col_idx 会像这样获得 -
col_idx = column_index(df, columns_to_select)
进一步优化
分析它显示瓶颈是使用 np.searchsorted 处理字符串,这是 NumPy 通常的弱点,即对字符串不太好。因此,为了克服这个问题并使用列名是单个字母的特殊情况,我们可以快速将它们转换为数字,然后将它们提供给 searchsorted 以加快处理速度。
因此,对于列名是单个字母并已排序的情况,获取基于整数的列 ID 的优化版本将是 -
def column_index_singlechar_sorted(df, query_cols):
c0 = np.fromstring(''.join(df.columns), dtype=np.uint8)
c1 = np.fromstring(''.join(query_cols), dtype=np.uint8)
return np.searchsorted(c0, c1)
这给了我们解决方案的修改版本,就像这样 -
a = df.values
col_idx = column_index_singlechar_sorted(df, columns_to_select)
out = pd.Series(a[np.arange(len(col_idx)), col_idx])
时间安排 -
In [149]: # Setup df with 26 uppercase column letters and many rows
...: import string
...: df = pd.DataFrame(np.random.randint(0,9,(1000000,26)))
...: s = list(string.uppercase[:df.shape[1]])
...: df.columns = s
...: idx = np.random.randint(0,df.shape[1],len(df))
...: columns_to_select = np.take(s, idx).tolist()
# With df.lookup from @MaxU's soln
In [150]: %timeit pd.Series(df.lookup(df.index, columns_to_select))
10 loops, best of 3: 76.7 ms per loop
# With proposed one from this soln
In [151]: %%timeit
...: a = df.values
...: col_idx = column_index_singlechar_sorted(df, columns_to_select)
...: out = pd.Series(a[np.arange(len(col_idx)), col_idx])
10 loops, best of 3: 59 ms per loop
鉴于 df.lookup 解决了一般情况,这可能是一个更好的选择,但本文中显示的其他可能的优化也很方便!