我在--pdbipython中使用该命令,因此当我调试代码并发生错误时,它会显示堆栈跟踪.很多这些错误来自于输入错误的numpy或pandas函数.堆栈跟踪从最新的帧开始,来自这些库的代码.up稍后重复5-10次命令我实际上可以看到我做错了什么,这将在90%的时间内立即显现(例如,使用列表而不是数组调用).
有没有办法指定调试器最初启动哪个堆栈帧?最旧的堆栈帧,或最初运行的python文件中的最新堆栈帧,或类似的.这对于调试来说会更有效率.
这是一个简单的例子
import pandas as pd
def test(df): # (A)
df[:,0] = 4 #Bad indexing on dataframe, will cause error
return df
df = test(pd.DataFrame(range(3))) # (B)
Run Code Online (Sandbox Code Playgroud)
为清楚起见,添加了回溯,(A),(B),(C)
In [6]: ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-66730543fac0> in <module>()
----> 1 import codecs, os;__pyfile = codecs.open('''/tmp/py29142W1d''', encoding='''utf-8''');__code = __pyfile.read().encode('''utf-8''');__pyfile.close();os.remove('''/tmp/py29142W1d''');exec(compile(__code, '''/test/stack_frames.py''', 'exec'));
/test/stack_frames.py in <module>()
6
7 if __name__ == '__main__':
(A)----> 8 df = test(pd.DataFrame(range(3)))
/test/stack_frames.py in test(df)
2
3 def test(df):
(B)----> 4 …Run Code Online (Sandbox Code Playgroud) 似乎有一个普遍的常识,即使用np.take速度比数组索引快得多。例如http://wesmckinney.com/blog/numpy-indexing-peculiarities/,快速numpy花式索引和Fast(er)numpy花式索引和缩减?。还有一些建议np.ix_在某些情况下更好。
我已经进行了一些分析,在大多数情况下,这似乎是正确的,尽管随着数组变大,差异会减小。
性能受阵列的大小,索引的长度(对于行)和采用的列数影响。行数似乎有最大的影响,即使索引为1D,数组中的列数也有影响。改变索引的大小似乎对方法之间的影响不大。
因此,问题有两个:1.为什么方法之间的性能会有如此大的差异?2.什么时候使用一种方法优于另一种方法?是否存在一些始终可以更好地工作的数组类型,顺序或形状?
有很多事情可能会影响性能,因此我在下面展示了其中的一些内容,并包括了用于尝试使其可再现的代码。
编辑我已经更新了图中的y轴,以显示值的完整范围。更清楚的是,差异小于一维数据的差异。
通过对比运行时间和行数,可以发现索引是相当一致的,并且有轻微的上升趋势。 take随着行数的增加,速度始终会变慢。

随着列数的增加,两者都会变慢,但take增加的幅度会更大(这仍然是一维索引)。

对于2D数据,结果相似。ix_还显示了使用情况,它似乎总体上具有最差的性能。

from pylab import *
import timeit
def get_test(M, T, C):
"""
Returns an array and random sorted index into rows
M : number of rows
T : rows to take
C : number of columns
"""
arr = randn(M, C)
idx = sort(randint(0, M, T))
return arr, idx
def draw_time(call, N=10, …Run Code Online (Sandbox Code Playgroud) 查找规范化的数据帧将删除用于分组的列,以便它不能在后续的groupby操作中使用.例如(编辑:更新):
df = pd.DataFrame({'a':[1, 1 , 2, 3, 2, 3], 'b':[0, 1, 2, 3, 4, 5]})
a b
0 1 0
1 1 1
2 2 2
3 3 3
4 2 4
5 3 5
df.groupby('a').transform(lambda x: x)
b
0 0
1 1
2 2
3 3
4 4
5 5
Run Code Online (Sandbox Code Playgroud)
现在,对于组中的大多数操作,"缺失"列变为新索引(然后可以使用reset_index或设置进行调整as_index=False),但是当使用变换时,它会消失,留下原始索引和没有密钥的新数据集.
编辑:这是我希望能够做到的一个内容
df.groupby('a').transform(lambda x: x+1).groupby('a').mean()
KeyError 'a'
Run Code Online (Sandbox Code Playgroud)
在pandas docs的示例中,使用函数根据索引进行拆分,这似乎完全避免了这个问题.或者,总是可以在groupby/transform之后添加列,但肯定有更好的方法吗?
更新:看起来reset_index/as_index仅适用于将每个组缩减为单个行的函数.从答案来看,似乎有几种选择
标题几乎说明了这一点。然而,方式matplotlib已经建立了,不可能简单地继承Axes并让它发挥作用。该对象从不直接使用,通常仅从调用或其他函数Axes返回。subplot
我想这样做有几个原因。首先,减少重复使用相似参数的重复绘图。像这样的东西:
class LogTemp(plt.Axes):
""" Axes to display temperature over time, in logscale """
def __init__(self, *args, **kwargs):
super.__init__(*args, **kwargs)
self.set_xlabel("Time (s)")
self.set_ylabel("Temperature(C)")
self.set_yscale('log')
Run Code Online (Sandbox Code Playgroud)
为此编写自定义函数并不困难,尽管它不会那么灵活。更大的原因是我想覆盖一些默认行为。作为一个非常简单的例子,考虑
class Negative(plt.Axes):
""" Plots negative of arguments """
def plot(self, x, y, *args, **kwargs):
super().plot(x, -y, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
或者
class Outliers(plt.Axes):
""" Highlight outliers in plotted data """
def plot(self, x, y, **kwargs):
out = y > 3*y.std()
super().plot(x, -y, **kwargs)
super().plot(x[out], y[out], marker='x', linestyle='', **kwargs)
Run Code Online (Sandbox Code Playgroud)
如果使用函数,尝试修改行为的多个方面很快就会变得混乱。
然而,我还没有找到一种方法来 …
python ×3
debugging ×1
indexing ×1
ipdb ×1
ipython ×1
matplotlib ×1
numpy ×1
pandas ×1
pdb ×1
python-3.x ×1