Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在某些情况下,如何计算numpy数组?_Python_Pandas_Numpy - Fatal编程技术网

Python 在某些情况下,如何计算numpy数组?

Python 在某些情况下,如何计算numpy数组?,python,pandas,numpy,Python,Pandas,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 = dat

我是编程新手,现在开始学习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………]
您的代码中没有注释。因此,我引入了变量
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]