【问题标题】:how can I apply the np.dot function on two lists in numpy pandas如何在 numpy pandas 的两个列表上应用 np.dot 函数
【发布时间】:2018-11-21 20:58:06
【问题描述】:

我有两个不同的列表,我必须在 python 中应用 numpy 的 np.dot 函数 我该怎么做?

list1=

array([[      nan,       nan],
       [ 0.000829,  0.000326],
       [-0.000149, -0.00033 ],
       ...,
       [-0.000757, -0.000737],
       [-0.000795, -0.00068 ],
       [-0.000788, -0.00069 ]])

list2 =

array([[      nan,       nan],
       [      nan,       nan],
       [-0.000829, -0.000326],
       ...,
       [ 0.000763,  0.000738],
       [ 0.000757,  0.000737],
       [ 0.000795,  0.00068 ]])

这是两个单独的列表列表

所以我想这样做:

np.dot([-0.000149, -0.00033 ], [-0.000829, -0.000326])

原来如此

np.dot(list1[3], list2[3])

它继续从一个列表中选择一个索引,从另一个列表中选择一个索引 那应该返回一维数组,问题是数据,它在两个单独的列表中,所以我需要一个列表中的索引和另一个列表中的一个索引,我知道它可以通过循环完成,但不确定怎么可能,

我希望现在很清楚

【问题讨论】:

  • @lucidbrot 是的,它是一种矩阵乘法
  • @timgeb 我还没有输出,但是在矩阵乘法之后它应该是一个一维列表
  • @id101112 好的,apparently the dot function is defined for more shapes than I expected 但建议使用list1 @ list2。您的问题需要一些关于np.dot(list1, list2) 有什么问题的额外信息
  • @id101112 list1 不是向量,它是矩阵。您如何期望矩阵乘法在不转置任一列表的情况下工作?而且我认为结果永远不可能是一维的。你有Nx2 形状的矩阵,所以它至少是二维的,对吧?
  • 让我再编辑一下我的问题,可能不是很清楚,

标签: python python-3.x numpy


【解决方案1】:

所以你的问题实际上是关于如何遍历列表并在每个对应的对上调用np.dot。这是一种方法,使用列表理解和zip:

>>> import numpy as np
>>> list1 = np.array([[1,2],[3,4]])
>>> list2 = list1.copy()
>>> list_of_results = [np.dot(a,b) for a,b in zip(list1, list2)]
>>> list_of_results
[5, 25]

如果您不熟悉列表理解,我建议您查一下。但是你也可以用一个简单的 for 循环来做到这一点:

assert list1.shape == list2.shape, "List shapes do not match"
results = []
for inner_list_index in range(list1.shape[0]):
    a = list1[inner_list_index]
    b = list2[inner_list_index]
    res = np.dot(a,b)
    results = results.append(res)

这可以减少到更少的行:

>>> assert list1.shape[0] == list2.shape[0]
>>> results = []
>>> for i in range(list1.shape[0]):
...     results.append(np.dot(list1[i], list2[i]))
...
>>> results
[5, 25]

请注意,这两种方法都返回正常的list,而不是 numpy ndarray。这是因为附加到 numpy 数组通常不会太快。您可以改用np.append()。或者,如果您再次需要将其作为 np 数组,则只需将 np.array() 应用于结果。

【讨论】:

  • 好的,是的,我只需要这条线[np.dot(a,b) for a,b in zip(list1, list2)]谢谢
  • 没问题!如果对您有帮助,请投票并接受我的回答:),如果有不清楚的地方,请随时提问
猜你喜欢
  • 1970-01-01
  • 2014-07-16
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 2018-06-06
  • 2021-02-03
相关资源
最近更新 更多