小编mib*_*ibm的帖子

Django在模型中"无法设置属性"

我有一个像这样的模型:

class MyReport(models.Model):
    group_id    = models.PositiveIntegerField(blank=False, null=False)
    test        = models.ForeignKey(Test, on_delete=models.CASCADE)
    owner       = models.ForeignKey(User, editable=False, default=get_current_user, on_delete=models.CASCADE)

    user_objects = UserFilterManager()

    @property
    def location(self):
        return self.test.location
Run Code Online (Sandbox Code Playgroud)

我添加了一个位置属性.我在运行时遇到此错误.我只粘贴了我最近一次调用的部分,在这种情况下是len()(我知道,使用count代替).

  File "C:\Python27\Lib\site-packages\django\db\models\query.py", line 240, in __len__
    self._fetch_all()
  File "C:\Python27\Lib\site-packages\django\db\models\query.py", line 1074, in _fetch_all
    self._result_cache = list(self.iterator())
  File "C:\Python27\Lib\site-packages\django\db\models\query.py", line 75, in __iter__
    setattr(obj, attr_name, row[col_pos])
AttributeError: can't set attribute
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么会出错?如果我称之为locationx,则没有错误.

Django有一些特殊的属性定义规则吗?

我怎么调试这个?

我添加了属性,因为我添加了测试间接,并希望尽可能少地更改代码.我当然可以,只是改变每个report.locationreport.test.location,但是这是一个麻烦.如果我可以为数据库搜索定义别名,那将是很好的,所以我需要更改它们.

编辑:回答评论:

  1. 我不想设置值,我只想要一个属性(getter).我希望能够report.location改为添加间接report.test.location(不想更改位置在报表模型中的现有代码).
  2. self.test.location和 …

python django

16
推荐指数
1
解决办法
7905
查看次数

在熊猫中,如何查找累积总和大于阈值的行/索引?

我想找到某列中值的累加总和超过阈值的行(索引)。

我可以并且确实使用一个简单的循环来找到此位置,如下所示:

def sum_to(df, col, threshold):
    s = 0
    for r in df.iterrows():
        if s + r[1][col] > threshold:
            return r[0]
        else:
            s += r[1][col]

    return len(df)
Run Code Online (Sandbox Code Playgroud)

但是,我想知道在Pandas中是否有更好/更精巧的方法来实现这一目标。

python pandas

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

numpy.ndarray 稀疏矩阵到密集

我想对一些打包为 a 的数据运行sklearn's RandomForestClassifier,而这些数据numpy.ndarray恰好是稀疏的。打电话fitValueError: setting an array element with a sequence.。从其他帖子我了解到随机森林无法处理稀疏数据。

我希望该对象有一个todense方法,但它没有。

>>> X_train
array(<1443899x1936774 sparse matrix of type '<class 'numpy.float64'>'
    with 141256894 stored elements in Compressed Sparse Row format>,
      dtype=object)
>>> type(X_train)
<class 'numpy.ndarray'>
Run Code Online (Sandbox Code Playgroud)

我尝试用 SciPy 包装它,csr_matrix但这也会产生错误。

有没有办法让随机森林接受这些数据?(不确定密集实际上是否适合内存,但那是另一回事......)

编辑 1

产生错误的代码是这样的:

X_train = np.load('train.npy') # this returns a ndarray
train_gt = pd.read_csv('train_gt.csv')

model = RandomForestClassifier()
model.fit(X_train, train_gt.target)
Run Code Online (Sandbox Code Playgroud)

至于使用的建议toarray(),ndarray 没有这样的方法。 AttributeError: 'numpy.ndarray' object has no …

python numpy scikit-learn

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

标签 统计

python ×3

django ×1

numpy ×1

pandas ×1

scikit-learn ×1