小编Jon*_*løv的帖子

Python类@property:使用setter但是避开getter?

在python类中,@ property是一个很好的装饰器,可以避免使用显式的setter和getter函数.然而,它的成本是"经典"类功能的2-5倍.在我的情况下,在设置属性的情况下这是非常好的,与设置时需要完成的处理相比,开销是微不足道的.

但是,在获得房产时我不需要处理.它总是只是"回归自我.属性".是否有一种优雅的方式来使用setter但不使用getter,而不需要使用不同的内部变量?

为了说明,下面的类具有属性"var",它指的是内部变量"_var".它需要更长的时间称为"VAR"比"_var"但它会是很好,如果开发者和用户都可以只使用"无功",而无需守得的"_var"的轨道.

class MyClass(object):
  def __init__(self):
    self._var = None

  # the property "var". First the getter, then the setter
  @property
  def var(self):
    return self._var
  @var.setter
  def var(self, newValue):
    self._var = newValue
    #... and a lot of other stuff here

  # Use "var" a lot! How to avoid the overhead of the getter and not to call self._var!
  def useAttribute(self):
    for i in xrange(100000):
      self.var == 'something'
Run Code Online (Sandbox Code Playgroud)

对于那些感兴趣的人,在我的电脑上调用"var"平均需要204 ns,而调用"_var"平均需要44 ns.

python properties class timing

49
推荐指数
3
解决办法
2万
查看次数

生成具有固定均值和sd的随机数

当使用rnorm(或runif等)在R中生成随机数时,它们很少具有精确的均值和SD作为它们的采样分布.是否有任何简单的一线或二线为我这样做?作为一个初步的解决方案,我已经创建了这个函数,但它似乎应该是R或某个包的本机.

# Draw sample from normal distribution with guaranteed fixed mean and sd
rnorm_fixed = function(n, mu=0, sigma=1) {
  x = rnorm(n)  # from standard normal distribution
  x = sigma * x / sd(x)  # scale to desired SD
  x = x - mean(x) + mu  # center around desired mean
  return(x)
}
Run Code Online (Sandbox Code Playgroud)

为了显示:

x = rnorm(n=20, mean=5, sd=10)
mean(x)  # is e.g. 6.813...
sd(x)  # is e.g. 10.222...

x = rnorm_fixed(n=20, mean=5, sd=10)
mean(x)  # …
Run Code Online (Sandbox Code Playgroud)

random r mean standard-deviation

20
推荐指数
1
解决办法
3万
查看次数

逐行编辑pandas数据帧

蟒蛇的大熊猫很整洁.我正在尝试用pandas-dataframe替换字典列表.但是,我想知道有一种方法可以在for循环中逐行更改值吗?

这是非熊猫dict-version:

trialList = [
    {'no':1, 'condition':2, 'response':''},
    {'no':2, 'condition':1, 'response':''},
    {'no':3, 'condition':1, 'response':''}
]  # ... and so on

for trial in trialList:
    # Do something and collect response
    trial['response'] = 'the answer!'
Run Code Online (Sandbox Code Playgroud)

...现在trialList包含更新的值,因为它trial引用了那个.非常便利!但是这些名单是非常不方便的,特别是因为我希望能够以列为单位计算大熊猫擅长的东西.

所以从上面给出了trialList,我可以通过做一些类似熊猫的事情来做得更好:

import pandas as pd    
dfTrials = pd.DataFrame(trialList)  # makes a nice 3-column dataframe with 3 rows

for trial in dfTrials.iterrows():
   # do something and collect response
   trials[1]['response'] = 'the answer!'
Run Code Online (Sandbox Code Playgroud)

......但trialList在这里保持不变.有没有一种简单的方法可以逐行更新值,也许等同于dict-version?重要的是它是逐行的,因为这是一个实验,其中参与者被呈现大量的试验并且在每个单独的试验中收集各种数据.

python trial pandas

14
推荐指数
1
解决办法
4万
查看次数

打印没有行和列索引的矩阵

如果我打印一个矩阵,它会在控制台中显示行和列索引.例如

> print(diag(3))
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1
Run Code Online (Sandbox Code Playgroud)

如何抑制列和行索引?就是这样的:

> print(diag(3), indices=FALSE)
1    0    0
0    1    0
0    0    1
Run Code Online (Sandbox Code Playgroud)

我可以看到cwhmisc包应该包含一个printM函数来根据文档执行此操作但是当我加载cwhmisc时它不存在.此外,这似乎是你应该能够在基地R的东西.

printing r matrix indices

11
推荐指数
2
解决办法
6614
查看次数

Barplot有显着的差异和相互作用?

我想想象我的数据和ANOVA统计数据.通常使用带有添加线条的条形图来指示显着的差异和相互作用.你怎么用R做这样的情节?

这就是我想要的:

显着差异:

显着差异

重要的互动:

重要的互动

背景

我目前正在使用barplot2{ggplots}绘制条形图和置信区间,但我愿意使用任何包/程序来完成工作.为了得到我目前使用的统计数据TukeyHSD{stats}pairwise.t.test{stats}对差异和方差分析功能(一个aov,ezANOVA{ez},gls{nlme})的相互作用.

只是为了给你一个想法,这是我目前的情节: 带有CI的barplot2

plot interaction r significance

10
推荐指数
1
解决办法
2万
查看次数

在data.frame中查找字符串

如何在data.frame中搜索字符串?作为一个最小的例子,我如何在这个data.frame中找到'horse'的位置(列和行)?

> df = data.frame(animal=c('goat','horse','horse','two', 'five'), level=c('five','one','three',30,'horse'), length=c(10, 20, 30, 'horse', 'eight'))
> df
  animal level length
1   goat  five     10
2  horse   one     20
3  horse three     30
4    two    30  horse
5   five horse  eight
Run Code Online (Sandbox Code Playgroud)

...所以第4行和第5行的顺序错误.任何允许我识别'horse'已经转移到level第5行的length列和第4行的列的输出都是好的.也许:

> magic_function(df, 'horse')
col       row
'animal', 2
'animal', 3
'length', 4
'level',  5
Run Code Online (Sandbox Code Playgroud)

以下是我想要使用的内容:我有一个非常大的数据框(大约60列,20.000行),其中一些列混淆了一些行.为了找出订单错误的不同方式,眼球太大了,所以搜索会很好.我将使用此信息将数据移动到这些行的正确列.

string r dataframe

8
推荐指数
2
解决办法
2万
查看次数

在64位linux上安装python 32位

我基本上有两个问题:

  1. 你如何在Linux上安装32位python和64位python?
  2. 如何从下面的失败尝试中修复损坏的系统?

我只是尝试在linux mint 16上安装32位python和我的64位python.它不像我希望的那样直接(类似sudo apt-get install python32会很好)但是经过一些谷歌搜索后我下载了python 2.7.6并执行了以下操作:

sudo apt-get install ia32-libs gcc-multilib checkinstall
CC="gcc -m32" LDFLAGS="-L/lib32 -L/usr/lib32 -Lpwd/lib32 -Wl,-rpath,/lib32 -Wl,-rpath,/usr/lib32" ./configure --prefix=/opt/pym32
make
sudo checkinstall
Run Code Online (Sandbox Code Playgroud)

应该让我能够像这样运行32位og 64bit(默认):

python -c 'import sys; print sys.maxint'
/opt/pym32/bin/python -c 'import sys; print sys.maxint'
Run Code Online (Sandbox Code Playgroud)

...但是/ opt/pym32 /甚至没有创建.更糟糕的是,我的系统现在报告了29个破坏的依赖项,表明新的python取代了旧的python或类似的东西.为了解决这个问题,aptitude建议我删除一大堆我需要的软件包并安装一大堆我不需要的软件包.

如果出现问题,我使用checkinstall而不是make install能够反向/卸载,但卸载/重新安装python将因为依赖性损坏而无法工作.有没有办法摆脱这个烂摊子?

linux dependencies install 32bit-64bit python-2.7

6
推荐指数
1
解决办法
6831
查看次数

Pythonic方式来保存相关变量?

我经常有一组(语义上)相关的动态变量,这些变量可以通过多种方法访问并在运行时更改.我目前正在三种突出其"家庭"的方式之间波动,并减少main中的概念混乱:变量名前缀,使用类或使用字典.

这些中的任何一种通常是首选的(即pythonic)还是完全不同的东西?我对课程略有偏好:

# Prefix
key_bindings_chars = {'right': '->', 'left':'<-'}
key_bindings_codes = ['smooth', 'spiky']
key_bindings_hints = ['Smooth protrutions', 'Spiky protrutions']

print(key_bindings_chars['right'])

# As a class
class key_bindings(object):
    chars = {'right': '->', 'left':'<-'}
    codes = ['smooth', 'spiky']
    hints = ['Smooth protrutions', 'Spiky protrutions']

print(key_bindings.chars['right'])

# As a dict
key_bindings = {
    'chars': {'right': '->', 'left':'<-'},
    'codes': ['smooth', 'spiky'],
    'hints': ['Smooth protrutions', 'Spiky protrutions']
}

print(key_bindings['chars']['right'])
Run Code Online (Sandbox Code Playgroud)

python grouping

6
推荐指数
1
解决办法
89
查看次数

尽早返回 dplyr 管道结果

编码时,我经常想检查我正在处理的管道的中间结果。如果我正在处理长管道的早期部分,则需要多次点击/鼠标才能有选择地运行并保存结果。有没有一种巧妙的方法可以做类似以下的事情?

library(dplyr)
result = mtcars |>
  # Testing this step
  filter(cyl == 4) |>
  return_early() |>

  # I don't want to run the rest of the pipeline
  group_by(gear) |>
  summarise()
Run Code Online (Sandbox Code Playgroud)

这样执行后,result将保持结果return_early()而不执行管道的其余部分?

请注意,我询问的是一种保存中间输出并停止评估的便捷方法。如果您对打印感兴趣,请参阅此处此处

debugging pipeline r dplyr

6
推荐指数
1
解决办法
99
查看次数

CSS:"float:bottom"如果有可用的垂直空间."浮动:离开"否则

我有两个非常窄(宽度:400像素)的div,如果浏览器窗口中有足够的垂直空间,则应垂直堆叠.如果浏览器高度太小并且有足够的空间,则"底部div"应浮动到顶部div的右侧.

从某种意义上说,我要求与"浮动:左"相反.float:如果浏览器窗口中有足够的水平空间,则left align divs水平,如果只有其他可用空间,则只有float divs低于其他.

谢谢你的任何建议!

html css css-float

5
推荐指数
1
解决办法
1772
查看次数