python - Python Numpy:对 numpy 对象数组执行算术运算
问题描述
我在数据库中保存了多个数据值。我只想执行算术动作。以下是数据样本:-
items = [
[1,2,3,4,5],
"+",
5
]
我有上面提到的数据数组。我可以执行算术运算吗?实际上,我想像这样执行上面的数据
代码
from numpy import np
result = np.array([1,2,3,4,5]) + np.double(5)
print(result)
输出
[ 6. 7. 8. 9. 10.]
提前致谢。
解决方案
正如评论中所指出的,意图很难处理。但假设有以下约束:
输入:
- 第一项始终是列表,int 或 float
- 第二项始终是运算符(+、-、/、* 等...)
- 第三项总是一个列表,int 或 float
逻辑:
- 如果第一项和第三项是列表,则它们具有相同的长度
您可以使用numexpr库来解决您的问题,如下所示:
import numexpr as ne
import numpy as np
def parser(items):
a, operator, b = items
a = np.array(a)
b = np.array(b)
return ne.evaluate(f"a {operator} b")
一些示例和测试:
tests = [
{
'items': [[1, 2, 3, 4, 5], '+', 5], # Integer
'answers': [6, 7, 8, 9, 10]
},
{
'items': [[1, 2, 3, 4, 5], '+', 5.], # float
'answers': [6., 7., 8., 9., 10.]
},
{
'items': [[1, 2, 3, 4, 5], '*', 5], # multiplication
'answers': [5, 10, 15, 20, 25]
},
{
'items': [[1, 2, 3, 4, 5], '+', [2, 3, 4, 5, 6]], # list addition
'answers': [3, 5, 7, 9, 11]
},
]
for test in tests:
reply = parser(test['items'])
assert all(x == y for x, y in zip(reply, test['answers']))
print(reply)
输出:
[ 6 7 8 9 10]
[ 6. 7. 8. 9. 10.]
[ 5 10 15 20 25]
[ 3 5 7 9 11]