简体   繁体   English

如何在python熊猫中找到带有多索引的至少两个数据框列?

[英]How do i find the minimum of two dataframe columns with multi-indices in python pandas?

I have got two pandas Dataframes df1 and df2 . 我有两个熊猫Dataframe df1df2 df1 has a multi-index: df1具有多重索引:

                  A   
instance index
a        0        10 
         1        11  
         2        7
b        0        8
         1        9
         2        13

The frame df2 has the same first-level index as df1 : 框架df2具有与df1相同的第一级索引:

              B   
instance 
a             5 
b             12

I want to do two things: 我想做两件事:

1) Assign the values in df2 to the all the rows of df1 1)将df2的值分配给df1的所有行

                  A    B
instance index
a        0        10   5
         1        11   5
         2        7    5
b        0        8    12
         1        9    12
         2        13   12

2) Create a dataframe object that represents the minimum of values in A and B without concatenating the two dataframes like above: 2)创建一个数据框对象,该对象表示AB的最小值,而不必像上面那样将两个数据框并置:

min(df1,df2):
                  min   
instance index
a        0        5   
         1        5   
         2        5   
b        0        8    
         1        9    
         2        12   

For your first request, you can use DataFrame.join : 对于第一个请求,可以使用DataFrame.join

>>> df1.join(df2)
                 A   B
instance index        
a        0      10   5
         1      11   5
         2       7   5
b        0       8  12
         1       9  12
         2      13  12

For your second, you can simply call min(axis=1) on that object: 第二秒钟,您只需在该对象上调用min(axis=1)

>>> df1.join(df2).min(axis=1).to_frame("min")
                min
instance index     
a        0        5
         1        5
         2        5
b        0        8
         1        9
         2       12

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

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