【发布时间】:2023-12-01 04:03:01
【问题描述】:
我刚开始使用 numpy 数组和 panda 数据帧,我正在做一个练习项目,但遇到了一些问题。我有一个熊猫数据框,我将它的行传递给一个函数来做一些工作。该函数接受两个不同的数组,一个标记为最佳和最差,然后创建一个新向量来比较总和。从那里它将返回 pandas.apply 已传递的当前数组,或者它将返回基于 sum() 最低的新向量。这将创建一个新的 python 数组,该数组最后需要是 20x5 的矩阵。该函数工作正常,但返回的数据帧需要转换为大小为 (20 x 5) 的 python 数组以供进一步工作,当调用 np.array() 时,它将其转换为大小为 (20,) 的数组.我认为只使用 .reshape(20,5) 会起作用,因为它有足够的元素可以使用,但它没有,它只是在运行时失败。感谢任何帮助,因为我找不到任何可以帮助我理解为什么会发生这种情况的东西。
(错误,正如许多人通过阅读上面所猜到的那样:“无法将大小为 20 的数组重新整形为形状 (20,5)”)
我的程序中显示它的代码除外(可以自己运行):
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed=22)
df = pd.DataFrame(rng.random((20,5)))
def new_vectors(current, best, worst):
#convert current to numpy array
current = current.to_numpy()
#construct a new vector to check
new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current)))))))
#get the new sum for the new and old vectors
summed = current.sum()
newsummed = new.sum()
#return the smallest one
return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten()
z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1))
z.reshape(20,5) #I know reshape() creates a copy, just here to show it doesn't work regardless
【问题讨论】:
-
z.reshape(20,5)返回一个新数组。它不能就地工作。阅读文档:numpy.org/doc/stable/reference/generated/numpy.reshape.html -
您返回一个形状为
(20,)的array of arrays。您无法将(20,)重塑为(20,5) -
对 hpaulj,我知道它没有,我只是把它放在那里表明它根本不起作用:也就是它永远不会超过那条线。
-
致 Michael,有没有办法将数据转换为不同的形状,或者创建一个大小为 20x5 的不同数组,并将这 100 个数据块映射到它?
-
您能否提供一个仅使用
(3,2)输入数组的结果示例?
标签: python arrays pandas numpy reshape