我需要提取matplotlib.lines.Line2D对象的样式信息以在matplotlib.pyplot.plot()调用中使用它。并且(如果可能的话)我想以一种比从Line2D.properties()输出中过滤与样式相关的属性更优雅的方式来实现。
代码可能像这样:
import matplotlib.pyplot as plt
def someFunction(a, b, c, d, **kwargs):
line = plt.plot(a, b, marker='x', **kwargs)[0]
plt.plot(c, d, marker='o', **kwargs) # the line I need to change
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我想用相同的样式(包括颜色)绘制两条线,但使用不同的标记。另外,plot()除非颜色已明确指定为关键字参数,否则我希望能够使用该功能的“自动着色”功能。
规范方法(使用np.vectorize())在空数组的情况下不起作用 - 它以以下结尾IndexError: index 0 is out of bounds for axis 0 with size 0:
>>> def f(x):
... return x + 1
...
>>> F = np.vectorize(f)
>>> F(np.array([]))
[Traceback removed]
IndexError: index 0 is out of bounds for axis 0 with size 0
Run Code Online (Sandbox Code Playgroud)
目前我使用
>>> np.array([f(x) for x in X])
Run Code Online (Sandbox Code Playgroud)
但我正在寻找更优雅的解决方案(和高效).在Python 2中,我可以选择
>>> np.array(map(f, X))
Run Code Online (Sandbox Code Playgroud)
但它在Python 3中失败了.
[编辑]
问题在NumPy阵列的每个单元的函数的有效评估中没有答案,因为:
vectorise 失败,A(i, j) := f(A(i, j)).我需要将大量 (1 440 000 000) 行附加到pandas.DataFrame.
我预先知道行数,因此我可以预先分配它,然后以类似于 C 的方式填充数据。
到目前为止,我最好的想法是相当丑陋的:
>>> N = 1000000
>>> sham = [-1] * (N * len(THRESHOLDS) * len(OBJECTS)) # 1440000000
>>> DATA = pd.DataFrame({'threshold': pd.Categorical(sham, categories=THRESHOLDS, ordered=True),
... 'expected': pd.Series(sham, dtype=np.float16),
... 'iteration': pd.Series(sham, dtype=np.int32),
... 'analyser': pd.Categorical(sham, categories=ANALYSERS),
... 'object': pd.Categorical(sham, categories=OBJECTS),
... },
... columns=['threshold', 'expected', 'iteration', 'analyser', 'object'])
>>> ptr = 0
>>> for t in THRESHOLDS:
... for o in OBJECTS:
... for a in ANALYSERS:
... for …Run Code Online (Sandbox Code Playgroud) 我正在开发一个包含Cython扩展的软件包。
根据https://github.com/pypa/pip/issues/1958,我将使用setup_requires并推迟的导入Cython。我想出的最好的解决方案是致电setup()两次setup.py:
... # initial imports
setup(setup_requires=['cython'])
from Cython.Build import cythonize
bar = Extension('foo.bar', sources = ['bar.pyx'])
setup(name = 'foo',
... # parameters
ext_modules = cythonize([bar]),
... # more parameters
)
Run Code Online (Sandbox Code Playgroud)
但是我有一种感觉,setup()建议的名称只能被调用一次。像我一样多次叫它安全吗?
我不能只分发轮子,因为该软件包也将对Linux用户可用。
[编辑]
我也认为这个问题比处理编译器依赖性更为笼统。可能需要导入一些软件包(例如sphinx或pweave)来预处理一个软件包的描述。
我有一个大DataFrame对象(1,440,000,000 行)。我在内存(包括交换)限制下运行。
我需要提取具有特定字段值的行的子集。但是,如果我这样做:
>>> SUBSET = DATA[DATA.field == value]
Run Code Online (Sandbox Code Playgroud)
我以MemoryError异常或崩溃结束。有什么方法可以显式过滤行 - 无需计算中间掩码(DATA.field == value)?
我找到了DataFrame.filter()和DataFrame.select()方法,但它们对列标签/行索引而不是行数据进行操作。
当我尝试在Jupyter Notebook中调试我的代码时,%debug我点击了"最旧的帧".
> $HOME/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py(244)_xy_from_xy()
242 if x.shape[0] != y.shape[0]:
243 raise ValueError("x and y must have same first dimension, but "
--> 244 "have shapes {} and {}".format(x.shape, y.shape))
245 if x.ndim > 2 or y.ndim > 2:
246 raise ValueError("x and y can be no greater than 2-D, but have "
ipdb> up
> $HOME/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py(385)_plot_args()
383 x, y = index_of(tup[-1])
384
--> 385 x, y = self._xy_from_xy(x, y)
386
387 if self.command == 'plot':
ipdb> up
> …Run Code Online (Sandbox Code Playgroud) "0"标签跨越两个刻度之间,因为在直方图中仅有0的单独bin,而轴的其余部分是线性的以指示其他bin的边界.underbrace并不重要,但是应该有一些指示器"0"跨越整个bin.
到目前为止我找到的最接近的解决方案是"自己绘制"(如何在matplotlib中为条形图添加组标签?).我正在寻找.axvspan()相当于轴(.axvline()对于刻度线),就像用于标记的东西一样.axvspan().
运行我的 jupyter 笔记本时,ipython 内核(Python 3.8、Anaconda)不断死机并重新启动。
我想找出是什么原因导致它行为不当。遗憾的是,除了内核已死并重新启动之外,我找不到任何调试信息。
如何找到可能有助于事后分析的更详细信息?有没有错误日志之类的?
我知道我可以用方法length参数设置刻度的长度AxesSubplot.tick_params()。
如何确定某个轴的主要刻度的实际长度?
请假设长度可能会改变。
我定义了两个函数作为最小的工作示例。
\nIn [2]: A = np.random.random(10_000_000)\n\nIn [3]: def f():\n ...: return A.copy() * np.pi\n ...: \n\nIn [4]: def g():\n ...: B = A.copy()\n ...: B *= np.pi\n ...: return B\nRun Code Online (Sandbox Code Playgroud)\n它们都返回相同的结果:
\nIn [5]: assert all(f() == g())\nRun Code Online (Sandbox Code Playgroud)\n但我希望g()更快,因为增强赋值 (for A) 比乘法快 4 倍多:
In [7]: %timeit B = A.copy(); B * np.pi\n82.2 ms \xc2\xb1 301 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\nIn [8]: %timeit B = …Run Code Online (Sandbox Code Playgroud) 以下代码适用于 Python 2.7:
>>> class Derived(int):
... def __eq__(self, other):
... return int.__eq__(other)
...
>>> Derived(12) == 12.0
True
>>> Derived(12) == 13
False
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它会起作用,因为该self属性没有显式地提供给int.__eq__()方法调用。
[编辑]
到目前为止的答案表明,这是关于返回NotImplemented并self.__eq__(other)因此调用other.__eq__(self)。然后Derived(12) == Derived(12)我期望是一个不定式递归,但事实并非如此:
>>> Derived(12) == Derived(12)
True
Run Code Online (Sandbox Code Playgroud) 目前,我尝试使用 memory_profiler 模块来获取使用的内存,如下面的代码:
from memory_profiler import memory_usage
memories=[]
def get_memory(mem,ended):
if ended:
highest_mem=max(mem)
print highest_mem
else:
memories.append(mem)
def f1():
#do something
ended=False
get_memory(memory_usage(),ended)
return #something
def f2():
#do something
ended=False
get_memory(memory_usage(),ended)
return #something
#main
f1()
f2()
ended=True
get_memory(memory_usage(),ended) #code end
>>>#output
# output
# highest memory
Run Code Online (Sandbox Code Playgroud)
但是,它没有成功执行。当end=True 时卡住,发送memory_usage() 的值,结束get_memory 函数。它也没有显示任何错误。,只是等待了很长时间,然后我强制停止执行。任何人都知道更好的方法或解决方案?
python ×12
python-2.7 ×7
python-3.x ×7
matplotlib ×3
debugging ×2
numpy ×2
pandas ×2
axes ×1
axis-labels ×1
dataframe ×1
distutils ×1
ipdb ×1
ipython ×1
optimization ×1
pdb ×1
performance ×1
python-2.x ×1
setuptools ×1