首页 > 解决方案 > 在某些情况下如何计算 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变量中的行数

标签: pythonpandasnumpy

解决方案


您的代码中没有注释。所以我引入了变量weights1weights2result1result2来跟踪结果并比较逻辑。

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]

推荐阅读