我有这样一个数字矩阵:
[[ 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
得到这个结果是因为在每个循环中重新分配了
payment
。尝试将payment = cf[:i+1] / cpi[i]
更改为payment += cf[:i+1] / cpi[i]
当您将numpy添加到标记时,我认为更简单的方法是使用numpy:
相关问题 更多 >
编程相关推荐