我认为它没有区别,但我使用的是Python 2.7.
所以我的问题的一般部分如下:我virtualenv为每个项目使用一个单独的.我没有管理员权限,我也不想乱用系统安装的软件包.当然,我想使用轮子加速整个包的升级和安装virtualenv.如何构建一个仅在特定范围内满足依赖性的轮子virtualenv?
具体来说,发行
pip wheel -w $WHEELHOUSE scipy
Run Code Online (Sandbox Code Playgroud)
失败了
Building wheels for collected packages: scipy
Running setup.py bdist_wheel for scipy
Destination directory: /home/moritz/.pip/wheelhouse
Complete output from command /home/moritz/.virtualenvs/base/bin/python -c "import setuptools;__file__='/home/moritz/.virtualenvs/base/build/scipy/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /home/moritz/.pip/wheelhouse:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/moritz/.virtualenvs/base/build/scipy/setup.py", line 237, in <module>
setup_package()
File "/home/moritz/.virtualenvs/base/build/scipy/setup.py", line 225, in setup_package
from numpy.distutils.core import setup
ImportError: No module named numpy.distutils.core
----------------------------------------
Failed building …Run Code Online (Sandbox Code Playgroud) 当我有一个超过6个值的变量时,我的麻烦就开始了,因为这是ggplot2中scale_shape函数的当前最大值.
由于这个问题,我尝试了另一个变量,我只是围绕原始变量的长度.
这是我的示例代码:
dataf <- structure(list(Municipality = structure(c(2L, 4L, 10L, 11L, 6L, 8L, 3L, 1L, 5L, 9L, 7L), .Label = c("Boyuibe", "Cabezas", "Camiri", "Charagua", "Cuevo", "Gutierrez", "Huacaya", "Lagunillas", "Machareti", "Vallegrande", "Villa Vaca Guzman"), class = "factor"), Growth = c(3.05, 2.85, 0.14, 1.21, 1.59, 2.35, -0.41, 0.81, 0.9, 2.89, 1.8), Density = c(3.0390920594, 0.260984024187, 5.20069847261, 2.50828556783, 3.43964629267, 3.69768961375, 32.4496626479, 2.06145019368, 4.2139578988, 0.740736713557, 1.67034079825)), .Names = c("Municipality", "Growth", "Density"), class = "data.frame", row.names = c(NA, -11L))
dataf <- dataf[with(dataf, order(Municipality)), ]
# …Run Code Online (Sandbox Code Playgroud) 我对scipy.spatial.distance.pdist处理missing(nan)值的方式感到有点困惑.
所以,万一我弄乱了矩阵的维度,让我们把它弄清楚.来自文档:
这些点被排列为矩阵X中的m个n维行向量.
因此,让我们在10维空间中生成缺少值的三个点:
numpy.random.seed(123456789)
data = numpy.random.rand(3, 10) * 5
data[data < 1.0] = numpy.nan
Run Code Online (Sandbox Code Playgroud)
如果我计算这三个观测值的欧几里德距离:
pdist(data, "euclidean")
Run Code Online (Sandbox Code Playgroud)
我明白了:
array([ nan, nan, nan])
但是,如果我过滤掉所有缺少值的列,我会得到适当的距离值:
valid = [i for (i, col) in enumerate(data.T) if ~numpy.isnan(col).any()]
pdist(data[:, valid], "euclidean")
Run Code Online (Sandbox Code Playgroud)
我明白了:
array([ 3.35518662, 2.35481185, 3.10323893])
这样,我丢弃了比我想要的更多的数据,因为我不需要过滤整个矩阵,而只需要一次比较一对矢量.我可以制作pdist或类似的功能执行成对屏蔽,不知何故?
编辑:
由于我的完整矩阵相当大,我对这里提供的小数据集进行了一些时序测试.
1.)scipy功能.
%timeit pdist(data, "euclidean")
Run Code Online (Sandbox Code Playgroud)
10000 loops, best of 3: 24.4 µs per loop
2.)不幸的是,到目前为止提供的解决方案大约慢了10倍.
%timeit numpy.array([pdist(data[s][:, ~numpy.isnan(data[s]).any(axis=0)], "euclidean") for s in map(list, itertools.combinations(range(data.shape[0]), 2))]).ravel()
Run Code Online (Sandbox Code Playgroud)
1000 loops, best of …
我知道将数据帧列表合并为一个的基础知识,如前所述.但是,我对保持行名称的聪明方法感兴趣.假设我有一个相当相等的数据帧列表,并将它们保存在命名列表中.
library(plyr)
library(dplyr)
library(data.table)
a = data.frame(x=1:3, row.names = letters[1:3])
b = data.frame(x=4:6, row.names = letters[4:6])
c = data.frame(x=7:9, row.names = letters[7:9])
l = list(A=a, B=b, C=c)
Run Code Online (Sandbox Code Playgroud)
当我使用时do.call,列表名称与行名称组合:
> rownames(do.call("rbind", l))
[1] "A.a" "A.b" "A.c" "B.d" "B.e" "B.f" "C.g" "C.h" "C.i"
Run Code Online (Sandbox Code Playgroud)
当我使用任何一个时rbind.fill,bind_rows或者rbindlist行名称被数字范围替换:
> rownames(rbind.fill(l))
> rownames(bind_rows(l))
> rownames(rbindlist(l))
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9"
Run Code Online (Sandbox Code Playgroud)
当我从列表中删除名称时,do.call产生所需的输出:
> names(l) = NULL
> rownames(do.call("rbind", l))
[1] "a" …Run Code Online (Sandbox Code Playgroud) 说我想从a中删除对角线scipy.sparse.csr_matrix.这样做有效吗?我在sparsetools模块中看到有C返回对角线的功能.
def csr_setdiag_val(csr, value=0):
"""Set all diagonal nonzero elements
(elements currently in the sparsity pattern)
to the given value. Useful to set to 0 mostly.
"""
if csr.format != "csr":
raise ValueError('Matrix given must be of CSR format.')
csr.sort_indices()
pointer = csr.indptr
indices = csr.indices
data = csr.data
for i in range(min(csr.shape)):
ind = indices[pointer[i]: pointer[i + 1]]
j = ind.searchsorted(i)
# matrix has only elements up until diagonal …Run Code Online (Sandbox Code Playgroud) 与此问题类似,我numpy.timedelta64在 Pandas DataFrame 中有一个列。按本回答上述问题,有一种功能pandas.tslib.repr_timedelta64,其很好地显示在天,小时timedelta:分钟:秒。我只想在几天和几小时内格式化它们。
所以我得到的是以下内容:
def silly_format(hours):
(days, hours) = divmod(hours, 24)
if days > 0 and hours > 0:
str_time = "{0:.0f} d, {1:.0f} h".format(days, hours)
elif days > 0:
str_time = "{0:.0f} d".format(days)
else:
str_time = "{0:.0f} h".format(hours)
return str_time
df["time"].astype("timedelta64[h]").map(silly_format)
Run Code Online (Sandbox Code Playgroud)
这让我想要的输出,但我不知道是否有一个函数numpy或pandas类似datetime.strftime,它可以格式化numpy.timedelta64根据提供的一些格式字符串?
我试图进一步调整@Jeff 的解决方案,但它比我的答案慢得多。这里是:
days = time_delta.astype("timedelta64[D]").astype(int)
hours = time_delta.astype("timedelta64[h]").astype(int) % 24
result = days.astype(str)
mask = (days > 0) & (hours …Run Code Online (Sandbox Code Playgroud) 首先,我正在使用:
我已经设置了一个带有多态模型的可安装 Rails 引擎,我想在其他引擎中使用它。模型类如下所示:
module Geo
class Location < ApplicationRecord
belongs_to :locatable, polymorphic: true
end
end
Run Code Online (Sandbox Code Playgroud)
在我的规范中,我想确保我有一个有效的模型,但是,在引擎中我没有与Geo::Location.
我如何设置一个虚拟类来测试有效性(belongs_to需要存在)或者您使用过哪些好的测试策略?
让我们把鸭子留在池塘里.
为了说清楚,我正在使用Python 2.7.3.
我正在玩数字检查,并发现了一些我发现奇怪的事情:
In [1]: numbers.Number.mro()
Out[1]: [numbers.Number, object]
In [2]: numbers.Complex.mro()
Out[2]: [numbers.Complex, numbers.Number, object]
In [3]: numbers.Real.mro()
Out[3]: [numbers.Real, numbers.Complex, numbers.Number, object]
In [4]: numbers.Rational.mro()
Out[4]: [numbers.Rational, numbers.Real, numbers.Complex,
numbers.Number, object]
In [5]: numbers.Integral.mro()
Out[5]: [numbers.Integral, numbers.Rational, numbers.Real,
numbers.Complex, numbers.Number, object]
Run Code Online (Sandbox Code Playgroud)
这令我...适得其反,距离Python本身(有些矛盾int,float,complex刚刚从继承object直接):
In [6]: isinstance(int(), complex)
Out[6]: False
In [7]: isinstance(int(), numbers.Complex)
Out[7]: True
Run Code Online (Sandbox Code Playgroud)
然后我写了以下函数:
def numeric_check(num):
print "Is an int:", isinstance(num, int)
print "Is a float:", isinstance(num, float) …Run Code Online (Sandbox Code Playgroud) 我正在使用numpy.random.shuffle以计算二维数组的随机列的统计数据。Python代码如下:
import numpy as np
def timeline_sample(series, num):
random = series.copy()
for i in range(num):
np.random.shuffle(random.T)
yield random
Run Code Online (Sandbox Code Playgroud)
我得到的速度是这样的:
import numpy as np
arr = np.random.sample((50, 5000))
Run Code Online (Sandbox Code Playgroud)
%%timeit
for series in timeline_sample(rnd, 100):
np.sum(series)
Run Code Online (Sandbox Code Playgroud)
1 个循环,最好的 3 个:每个循环 391 毫秒
我试图对这个函数进行 Cythonize,但我不确定如何替换调用,np.random.shuffle并且该函数慢了 3 倍。有谁知道如何加速或替换它?它目前是我程序中的瓶颈。
赛通代码:
1 loops, best of 3: 391 ms per loop
我的电脑里有一个固定装置conftest.py文件中有一个具有三个参数的装置:
@pytest.fixture(scope="session",
params=[(33, 303), (303, 3003), (3003, 300003)],
ids=["small", "medium", "large"])
def complete(request):
np.random.seed(1234567890)
return np.random.rand(*request.param)
Run Code Online (Sandbox Code Playgroud)
现在,在特定的长时间运行的测试函数上,我想跳过“大”情况。
@pytest.mark.skipif(...)
def test_snafu(complete):
assert ...
Run Code Online (Sandbox Code Playgroud)
这有可能吗?
我已经使用 pytest 一段时间了,并且学会了喜欢参数化和夹具。第一次,我想测试多个具有分支继承结构的类。当然,我想为子类重用测试用例。假设我有以下包结构:
mock
??? pkg
? ??? child.py
? ??? grandchild.py
? ??? parent.py
??? tests
??? test_child.py
??? test_grandchild.py
??? test_parent.py
Run Code Online (Sandbox Code Playgroud)
如this SO question中所述,我可以使用夹具来提供正在测试的类的实例。但是,当我从另一个测试模块中导入测试类时,它 (a) 感觉这不是 pytest 方式,并且 (b) pytest 将运行导入类的所有测试方法,并作为继承测试类的一部分再次运行它们. 例如,文件test_child.py包含以下内容:
from test_parent import TestParent
class TestChild(TestParent):
def test_foo(self):
pass
def test_bar(self):
pass
Run Code Online (Sandbox Code Playgroud)
这会导致 pytest 运行TestParent一次测试方法(由于在模块中导入)加上另一次运行TestChild(由于其方法被继承)。
所以我看到两种方法:(1)不要继承基础测试类,而只是创建一个夹具,以便当前实例同时用于TestParent和TestChild,本质上:
import pytest
from pkg.child import Child
from test_parent import TestParent
@pytest.fixture(scope="class")
def instance():
return Child()
class TestChild(object):
def …Run Code Online (Sandbox Code Playgroud) python ×8
numpy ×3
scipy ×3
pytest ×2
r ×2
data.table ×1
diagonal ×1
distance ×1
dplyr ×1
fixture ×1
ggplot2 ×1
inheritance ×1
nan ×1
numbers ×1
pandas ×1
pip ×1
plyr ×1
python-2.7 ×1
python-wheel ×1
rspec-rails ×1
shuffle ×1
timedelta ×1
types ×1
virtualenv ×1