计算付款时出现意外结果

时间:2018-11-16 01:12:27

标签: python numpy

我有一个数字矩阵,如下所示:

[[    0.     771.98     0.   ...,   771.98     0.    1543.96]
 [ 1320.83  4782.33  1320.83 ...,  1954.45     0.    1954.45]
 [ 2043.61     0.    4087.22 ...,  4662.3   2907.82  1549.53]
 ..., 
 [  427.6      0.     427.6  ...,   427.6      0.     427.6 ]
 [  868.58  1737.16     0.   ...,   868.58   868.58   868.58]
 [    0.    1590.07     0.   ...,   787.75     0.       0.  ]]

我还有一个数字向量,看起来像这样:

0        771.98
1       1320.83
2       2043.61
3        736.03
4        948.03
5       1838.70
...

现在,我需要取每一行并除以向量。换句话说,取row1 = [ 0. 771.98 0. ..., 771.98 0. 1543.96]并除以向量771.98的第一个元素,得出的结果如下:

[[ 0.  1.  0.  1.  1.  1.  0.  5.  1.  0.  2.]]

我尝试过:

payment = []
index = 0
for i in range(len(cpi)):
    payment = cf[:i+1] / cpi[i]
print(payment[:1])

但是我明白了:

[[ 0.          1.60983442  0.          1.60983442  1.60983442  1.60983442
   0.          8.04917212  1.60983442  0.          3.21966885]]

有什么解决方法吗?

按照提供的答案,我尝试了两个建议。对于第一个建议,我得到此错误:

ValueError                                Traceback (most recent call last)
<ipython-input-15-3e5833506bde> in <module>()
      3 index = 0
      4 for i in range(len(cpi)):
----> 5     payment += cf[:i+1] / cpi[i]
      6 print(payment)
      7 # payment = np.divide(cf.T, cpi).T

ValueError: operands could not be broadcast together with shapes (0,) (1,11) 

对于第二个建议,我尝试了此方法:

payment = np.divide(cf.T, cpi).T
print(payment)

我收到此错误:

Exception                                 Traceback (most recent call last)
<ipython-input-16-f2ff3fa5409d> in <module>()
      4 #     payment += cf[:i+1] / cpi[i]
      5 # print(payment)
----> 6 payment = np.divide(cf.T, cpi).T
      7 print(payment)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in __array_wrap__(self, result, context)
    480         """
    481         return self._constructor(result, index=self.index,
--> 482                                  copy=False).__finalize__(self)
    483 
    484     def __array_prepare__(self, result, context=None):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in __init__(self, data, index, dtype, name, copy, fastpath)
    246             else:
    247                 data = _sanitize_array(data, index, dtype, copy,
--> 248                                        raise_cast_failure=True)
    249 
    250                 data = SingleBlockManager(data, index, fastpath=True)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in _sanitize_array(data, index, dtype, copy, raise_cast_failure)
   3025     elif subarr.ndim > 1:
   3026         if isinstance(data, np.ndarray):
-> 3027             raise Exception('Data must be 1-dimensional')
   3028         else:
   3029             subarr = _asarray_tuplesafe(data, dtype=dtype)

Exception: Data must be 1-dimensional

1 个答案:

答案 0 :(得分:2)

之所以获得此结果,是因为您在每个循环中都重新分配了payment。尝试将payment = cf[:i+1] / cpi[i]更改为payment += cf[:i+1] / cpi[i]

当您将numpy添加到标签中时,我认为更简单的方法是使用numpy:

import numpy as np
a = np.arange(9).reshape(-1,3)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]
b = np.arange(3) + 1
# [1 2 3]
print(np.divide(a.T, b).T)
# [[0.         1.         2.        ]
#  [1.5        2.         2.5       ]
#  [2.         2.33333333 2.66666667]]