numpy - 与ndarray相关的DataFrame.mul使用错误

标签 numpy pandas error-handling dataframe

我从本文Get dot-product of dataframe with vector, and return dataframe, in Pandas引用来使用DataFrame.mul。
我的问题代码是这样

df.mul(weight)

其中weight是形状为(17L,1L)的'numpy.ndarray'数据类型,打印结果为
[[  2.37005330e-07]
 [  2.80515078e-07]
 [  2.80267682e-07]
 [  2.79124521e-07]
 [  2.01799847e-07]
 [  2.71495529e-07]
 [  2.81640566e-07]
 [  2.30099310e-07]
 [  1.95221059e-07]
 [  2.10244387e-07]
 [  2.82483251e-07]
 [  2.29050342e-07]
 [  9.99996381e-01]
 [  8.95340469e-08]
 [  3.90767576e-08]
 [  2.31231511e-07]
 [  2.79852240e-07]]

其中df是形状为[20208行x 17列]的数据框对象,打印结果类似于
                     12&88    17&123 ....
modified datetime                        
2015-09-07 09:19:00  1.000000  1.000000  ....
2015-09-07 09:30:00  1.000000  1.000000  ....
2015-09-07 09:31:00  1.000000  0.974714  ....
2015-09-07 09:32:00  1.000000  0.978203  ....
2015-09-07 09:33:00  1.000000  0.978203  ....
2015-09-07 09:34:00  1.000000  0.990576  ....
....

但是当我执行df.mul(weight)时,它发生了
ValueError: Shape of passed values is (1, 17), indices imply (17, 20208)

我尝试了一个形状更简单的数组(17L,),并且使用df.mul。没有问题,所以我想知道是否应该将权重更改为数组的ndarray,但这对我来说很困难。如何更改?或者会有更好的主意来解决此问题?非常感谢您的帮助!

这是我的原始代码
   weight, means, stds = optimal_portfolio(result_framea.transpose())

   c , b= test.pairs_trade(load_path, sNo_list[0])
   result_frame = pd.DataFrame(index = c.index)
   for i, sNo in enumerate(sNo_list):
        c,b = test.pairs_trade(load_path, sNo)
        result_frame[sNo[0]+'&'+sNo[1]] = c['returns']
   df=result_frame.fillna(method='pad')

一切都很好,直到df.mul(weight)之后。再次谢谢你!

最佳答案

help(pd.DataFrame.mul):

mul(self, other, axis='columns', level=None, fill_value=None) unbound pandas.core.frame.DataFrame method

Multiplication of dataframe and other, element-wise (binary operator mul).

Equivalent to dataframe * other, but with support to substitute a fill_value for missing data in one of the inputs.



这表明在最简单的情况下,df.mul将仅对相应数组执行numpy风格的乘法。因此,您尝试将(20208,17)形状的数组与(17,1)形状之一相乘。这是行不通的。

array broadcasting在numpy中的工作方式是,具有某些奇异维度的数组可以被numpy自动扩展,以便在算术运算中将它们与其他更大的数组匹配。问题在于,如果其中一个数组的维数较少,则假定前导单例维数。

因此,例如,以下数组形状可以相乘/相加/相除/等在一起而不会出现问题:
  • (1,17)(20208,17),因为非单维度匹配
  • (17,)(20208,17),因为第一个与(1,17)隐式兼容(假定领先的单例尺寸)
  • (5,1,17)and(1,20208,17)(or just(20208,17)`)

  • 以下内容不能一起播放:
  • (1,16)(20208,17),因为尺寸不匹配
  • (16,) and(20208,17)because the mismatch is there even after implicitly expanding the first one to shape(1,16)`
  • (17,1)(20208,17)出于显而易见的原因

  • 问题是 Pandas 显示了您在问题中引用的神秘错误消息:

    ValueError: Shape of passed values is (1, 17), indices imply (17, 20208)



    在numpy中看起来像这样(尝试np.random.rand(17,1)*np.random.rand(20208,17)):

    ValueError: operands could not be broadcast together with shapes (17,1) (20208,17)



    后一个错误非常清楚,可能会为您省去很多麻烦。

    解决方案很简单:将权重数组reshape(17,1)形状(二维数组中的列 vector )更改为(17,)(一维数组)。可以使用更大的阵列进行广播。为此,只需使用维度参数reshape调用-1,告诉numpy为您确定1d数组的长度:
    df.mul(weight.reshape(-1))
    

    请注意,resut将与shape中的数据使用相同的df,但每列将与weight中的相应元素相乘。

    关于numpy - 与ndarray相关的DataFrame.mul使用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36607862/

    相关文章:

    python - 在给定阈值内提取高度相关变量的最佳方法是什么

    python - 数据 View 不显示 DataFrame 的索引,也不显示 numpy 数组中的行号

    java - R.string Resources $ NotFoundException在Android应用程序上的错误

    php - 撇号显示为�从Word Doc复制和粘贴文本时显示为菱形

    python - 将文件的行转换为 numpy 数组

    python - Python 中数组的 2D 和 3D 散点直方图

    python - 如何使用传统 python 或使用 pandas/numpy/sciy 在列表中按顺序选择第一次出现的重复项

    python - 在 Pandas 中,如果列最初为空,如何使用 fillna 将整个列填充为字符串?

    python - Pandas 和类别替换

    perl - 如何限制 DBIx::Error 中的堆栈跟踪?