熊猫多索引数据框条件列合并

时间:2019-02-23 12:27:58

标签: python pandas dataframe

我有2个多索引数据帧

df2 = pd.DataFrame({'Country': [ 'US', 'IT', 'FR'],
                'Unit': [ 'USD', 'EUR', 'EUR'],
                  'Location': [ 'Hawai', 'Torino', 'Paris'],
                  '2000': [666, 888,777],
                    '2002': [44,55,66]
                   })
df2.set_index(['Country','Unit','Location'],inplace=True)

df3 = pd.DataFrame({'Country': [ 'US', 'IT', 'FR'],
                'Unit': [ 'USD', 'EUR', 'EUR'],
                  '2018': [666, 888,777]
                   })
df3.set_index(['Country','Unit'],inplace=True)  
                       2000  2002
Country Unit Location            
US      USD  Hawai      666    44
IT      EUR  Torino     888    55
FR      EUR  Paris      777    66
              2018
Country Unit      
US      USD    666
IT      EUR    888
FR      EUR    777  

我希望有一个数据框结果,其中的thid列仅包含EUR值,另一个应保持空白,如下所示

                      2000  2002 2018
Country Unit Location                 
US      USD  Hawai      666    44     
IT      EUR  Torino     888    55  888
FR      EUR  Paris      777    66  777  

尝试级联,但不确定这是正确的方法吗?有什么想法吗?

1 个答案:

答案 0 :(得分:0)

joinDataFrame.xs一起用于<script lang="javascript" type="text/javascript"> var dropdown = document.getElementsByClassName("dropdown-btn"); var i; for (i = 0; i < dropdown.length; i++) { dropdown[i].addEventListener("click", function() { this.classList.toggle("active"); var dropdownContent = this.nextElementSibling; if (dropdownContent.style.display === "block") { dropdownContent.style.display = "none"; } else { dropdownContent.style.display = "block"; } }); } </script> 的第二级选择:

MultiIndex

详细信息:

df = df2.join(df3.xs('EUR', level=1, drop_level=False))
print (df)
                       2000  2002   2018
Country Unit Location                   
US      USD  Hawai      666    44    NaN
IT      EUR  Torino     888    55  888.0
FR      EUR  Paris      777    66  777.0

print (df3.xs('EUR', level=1, drop_level=False)) 2018 Country Unit IT EUR 888 FR EUR 777 中工作的解决方案-将reset_indexpandas 0.22.0和最后{{3 }}与DataFrame一起使用,以避免丢弃原始索引值:

join
相关问题