简体   繁体   English

在熊猫面板上广播乘法

[英]Broadcasting a multiplication across a pandas Panel

I have a pandas Panel that is long, wide, and shallow.我有一个长、宽、浅的熊猫面板。 In reality it's bigger but for ease of example, let's say it's 2x5x6:实际上它更大,但为了方便起见,假设它是 2x5x6:

panel=pd.Panel(pd.np.random.rand(2,3,6))

I have a Series that is the length of the shortest dimension - in this case 2:我有一个系列,它是最短维度的长度 - 在这种情况下为 2:

series=pd.Series([0,1])

I want to multiply the panel by the series, by broadcasting the series across the two other axes.我想通过在其他两个轴上广播系列来将面板乘以系列。

  1. Using panel.mul doesn't work, because that can only take Panel s or DataFrame s, I think使用panel.mul不起作用,因为我认为只能使用Panel s 或DataFrame s

    panel.mul(series) # returns None

  2. Using panel.apply(lambda x: x.mul(series), axis=0) works, but seems to do the calculation across every combination of series, in this case 3x6=18, but in reality >1m series, and so is extremely slow.使用panel.apply(lambda x: x.mul(series), axis=0)有效,但似乎对每个系列组合进行计算,在这种情况下为 3x6=18,但实际上 >1m 系列,所以是非常慢。

  3. Using pd.np.multiply seems to require a very awkward construction:使用pd.np.multiply似乎需要一个非常笨拙的构造:

    pd.np.multiply(panel, pd.np.asarray(series)[:, pd.np.newaxis, pd.np.newaxis])

Is there an easier way?有更容易的方法吗?

I don't think there's anything wrong conceptually with your last way of doing it (and I can't think of an easier way).我认为您的最后一种方式在概念上没有任何问题(而且我想不出更简单的方法)。 A more idiomatic way to write it would be一种更惯用的写法是

import numpy as np
panel.values * (series.values[:,np.newaxis,np.newaxis])

using values to return the underlying numpy arrays of the pandas objects.使用values返回 Pandas 对象的底层 numpy 数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM