【发布时间】:2016-09-10 00:48:01
【问题描述】:
我一直在探索如何优化我的代码并遇到了pandas.at 方法。根据documentation
基于标签的快速标量访问器
与 loc 类似,at 提供基于标签的标量查找。您也可以使用这些索引器进行设置。
所以我运行了一些样本:
设置
import pandas as pd
import numpy as np
from string import letters, lowercase, uppercase
lt = list(letters)
lc = list(lowercase)
uc = list(uppercase)
def gdf(rows, cols, seed=None):
"""rows and cols are what you'd pass
to pd.MultiIndex.from_product()"""
gmi = pd.MultiIndex.from_product
df = pd.DataFrame(index=gmi(rows), columns=gmi(cols))
np.random.seed(seed)
df.iloc[:, :] = np.random.rand(*df.shape)
return df
seed = [3, 1415]
df = gdf([lc, uc], [lc, uc], seed)
print df.head().T.head().T
df 看起来像:
a
A B C D E
a A 0.444939 0.407554 0.460148 0.465239 0.462691
B 0.032746 0.485650 0.503892 0.351520 0.061569
C 0.777350 0.047677 0.250667 0.602878 0.570528
D 0.927783 0.653868 0.381103 0.959544 0.033253
E 0.191985 0.304597 0.195106 0.370921 0.631576
让我们使用.at 和.loc 并确保我得到相同的东西
print "using .loc", df.loc[('a', 'A'), ('c', 'C')]
print "using .at ", df.at[('a', 'A'), ('c', 'C')]
using .loc 0.37374090276
using .at 0.37374090276
使用.loc测试速度
%%timeit
df.loc[('a', 'A'), ('c', 'C')]
10000 loops, best of 3: 180 µs per loop
使用.at测试速度
%%timeit
df.at[('a', 'A'), ('c', 'C')]
The slowest run took 6.11 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 8 µs per loop
这看起来是一个巨大的速度提升。即使在缓存阶段6.11 * 8也比180快很多
问题
.at 的限制是什么?我有动力使用它。文档说它类似于.loc,但它的行为并不相似。示例:
# small df
sdf = gdf([lc[:2]], [uc[:2]], seed)
print sdf.loc[:, :]
A B
a 0.444939 0.407554
b 0.460148 0.465239
print sdf.at[:, :] 的结果是 TypeError: unhashable type
即使意图相似,显然也不相同。
也就是说,谁能提供关于.at 方法可以做什么和不可以做什么的指导?
【问题讨论】:
-
仅供参考:python3 版本的字母、小写和大写常量均以 ascii_ docs.python.org/release/3.1.3/library/… 开头