简体   繁体   中英

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.

I have two 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 :

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. I need something pythonic avoiding using loop. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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