简体   繁体   English

将Django模型queryset转换为numpy矩阵

[英]Converting Django models queryset into a numpy matrix

I want to pull out a set of fields for objects in a Django queryset and convert them into a matrix with the fields as columns for some computation. 我想为Django queryset中的对象提取一组字段,并将它们转换为矩阵,这些字段作为列进行某些计算。 I've gotten to the point of : 我已经指出了:

qs = models.Devices.objects.all()

params = qs.values('b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8')

which returns a list of dictionaries ordered by object. 返回按对象排序的字典列表。

I want to know if there's a good way to convert these into rows of a numpy matrix and also if there is a way to keep an index of where these values are held in the db? 我想知道是否有一种好的方法可以将这些转换为numpy矩阵的行,并且是否有一种方法可以保留这些值在数据库中的保留位置的索引?

I want to do some calculations (sometimes different ones depending on the parameter type) and then eventually use the resultant vectors to populate/overwrite an existing column in the db such that the ordering is the same. 我想进行一些计算(有时取决于参数类型而有所不同),然后最终使用结果向量填充/覆盖db中的现有列,以使顺序相同。

You could 你可以

  1. Use the values_list() method to get a list of lists. 使用values_list()方法获取列表列表。 Include the id in the values. 在值中包含id
  2. Use list comprehension on the result of the query to remove the ids from the params and generate a list of ids . 对查询结果使用列表推导,以从params删除ID并生成ids列表。
  3. Use the params as the parameter for numpy.matrix() . 使用params作为numpy.matrix()的参数。
  4. Perform operations on the matrix. 在矩阵上执行操作。
  5. Iterate over the ids and save the values from each row of the matrix to the corresponding object. 遍历id,并将值从矩阵的每一行保存到相应的对象。

     import numpy as np qs = models.Devices.objects.all() params = qs.values_list('id', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8') ids = [arr.pop(0) for arr in params] matrix = np.matrix(params) # perform operations here for index, id in enumerate(ids): row = matrix[index].flat obj = qs.get(id=id) obj.b1 = row.next() obj.b2 = row.next() obj.b3 = row.next() obj.b4 = row.next() obj.b5 = row.next() obj.b6 = row.next() obj.b7 = row.next() obj.save() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM