python - 在某些情况下如何计算 numpy 数组?
问题描述
我是编程新手,开始学习 Python。我想问一些问题,例如我有这样的代码
import pandas as pd
from pandas.api.types import CategoricalDtype
import numpy as np
data = pd.DataFrame(np.array([[1, 1, 2, 3], [2, 2, 3, 3], [1, 1, 2, 1]]))
weights = np.array([0.1, 0.3, 0.5, 0.6])
n = data.max().max()
dummies = pd.get_dummies(data.T.astype(CategoricalDtype(categories=np.arange(1, n + 1))))
result = weights.dot(dummies).reshape(data.shape[0], n)
result = np.argmax(result, axis=1) + 1
result = np.sum(result)
print(result)
上述程序的结果是7
我要问的是如何,如果weight
变量有几行这样的。
weights = np.array([[0.1, 0.3, 0.5, 0.6],
[0.3, 0.1, 0.2, 0.4],
[0.4, 0.3, 0.1, 0.3]])
我应该更改语法的哪一部分?
我想要的结果是这样的
[7 .. .. .. .. ..]
<<这个结果取决于weight
变量中的行数
解决方案
您的代码中没有注释。所以我引入了变量weights1
、weights2
、result1
和result2
来跟踪结果并比较逻辑。
import pandas as pd
from pandas.api.types import CategoricalDtype
import numpy as np
data = pd.DataFrame(np.array([[1, 1, 2, 3], [2, 2, 3, 3], [1, 1, 2, 1]]))
weights1 = np.array([0.1, 0.3, 0.5, 0.6])
weights2 = np.array([[0.1, 0.3, 0.5, 0.6],
[0.3, 0.1, 0.2, 0.4],
[0.4, 0.3, 0.1, 0.3]])
n = data.max().max()
dummies = pd.get_dummies(data.T.astype(CategoricalDtype(categories=np.arange(1, n + 1))))
result1 = weights1.dot(dummies).reshape(data.shape[0], n)
result2 = weights2.dot(dummies).reshape(data.shape[0], n, weights2.shape[0])
result1 = np.argmax(result1, axis=1) + 1
result2 = np.argmax(result2, axis=2) + 1
result1 = np.sum(result1)
result2 = np.sum(result2,1)
print(result1)
print(result2)
输出:
7
[7 5 4]
推荐阅读
- javascript - 取消选中单选按钮时,电子邮件字段消失
- .net - 如何在 .NET Core 的 IConfiguration 中获取自定义环境变量
- html - 在salesforce中从字符串中取出子字符串
- gps - GPS Tracking: SOCKET PROGRAMMING :
- javascript - I'm I nesting these if/else if statements correctly in JavaScript?
- c# - ContactStore ContactChanged event is not firing when Modifying Contacts
- macos - Explain fst_posmode, difference between F_PEOFPOSMODE and F_VOLPOSMODE?
- java - Liferay生成的数据库的名称是什么?
- c# - 为什么飞行相机永远不会在地形上的航路点之间飞行?
- module - 如何跨子例程处理模块中的 Fortran 全局可分配变量