简体   繁体   English

通过将两个DataFrame与Pandas相乘来构建面板

[英]Build Panel from the multiplication of two DataFrames with Pandas

My purpose is a kind of element-wise multiplication between two DataFrames returning a Panel. 我的目的是在两个返回Panel的DataFrame之间进行按元素的乘法。

I have two DataFrames : 我有两个DataFrames:

a = pd.DataFrame(1, index=['a','b','c'], columns=[0,1,2,3,4])
Out[50]: 
     0    1    2    3    4
a  NaN  NaN  NaN  NaN  NaN
b  NaN  NaN  NaN  NaN  NaN
c  NaN  NaN  NaN  NaN  NaN

b = pd.DataFrame(index=[0,1,2,3,4], columns=['X', 'Y', 'Z'])
Out[53]: 
     X    Y    Z
0  NaN  NaN  NaN
1  NaN  NaN  NaN
2  NaN  NaN  NaN
3  NaN  NaN  NaN
4  NaN  NaN  NaN

and I want to get a Panel p such as : 我想得到一个Panel p例如:

p.items = [0,1,2,3,4]
p.major_axis = ['a','b','c']
p.minor_axis = ['X', 'Y', 'Z']

where : 在哪里:

p.loc[3, 'b', 'Z'] = a.loc['b', 3] * b.loc[3, 'Z']

And of course, both DataFrame are filled with real values. 当然,两个DataFrame都填充有实数值。 I need something pythonic avoiding using loop. 我需要一些pythonic避免使用循环。 Do you have any idea about how to perform that ? 您对如何执行此操作有任何想法吗?

Thanks for your help 谢谢你的帮助

Finally, a simple loop is pretty efficient if you don't have too many items : 最后,如果您没有太多的项目,那么简单的循环会非常有效:

    p = pd.Panel(items=a.columns, major_axis=a.index, minor_axis=b.columns)
    for x in a.index:
        p.loc[:, :, c] = a.loc[x, :] * b

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

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