[英]Can I subtract two pandas dataframes with different indexes in both axes?
[英]Pandas Two Dataframes subtract based on multi indexes
我有兩個DFS,我想根據多索引減去
profitDf
Company Product Amount
Google Pixel 2 3000
Microsoft Window 10 4000
Amazon AWS 10000
costDf
Company Product Amount
Google Pixel 2 10000
Microsoft Window 10 1000
ASUS Router 50000
我想產生一個如下的數據框
differenceDf
Company Product Difference
Google Pixel 2 -7000
Microsoft Window 10 3000
Amazon AWS 10000
ASUS Router -50000
我努力了
profitDf.set_index(['Company','Product']).sub(costDf.set_index(['Company','Product']), fill_value=0).reset_index()
但它顯示NotImplementedError: merging with both multi-indexes is not implemented
謝謝您的幫助
由於它是使用merge
多個索引
pdf.merge(cdf,on=['Company','Product'],how='outer').fillna(0).eval('Diff=Amount_x-Amount_y')
Out[205]:
Company Product Amount_x Amount_y Diff
0 Google Pixel2 3000.0 10000.0 -7000.0
1 Microsoft Window10 4000.0 1000.0 3000.0
2 Amazon AWS 10000.0 0.0 10000.0
3 ASUS Router 0.0 50000.0 -50000.0
或使用pivot
pdf.pivot(*pdf.columns).sub(cdf.pivot(*cdf.columns),fill_value=0).stack()
Out[218]:
Company Product
ASUS Router -50000.0
Amazon AWS 10000.0
Google Pixel2 -7000.0
Microsoft Window10 3000.0
dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.