简体   繁体   English

Python Pandas-基于单个索引的具有多个索引的逻辑索引数据框

[英]Python Pandas - Logical indexing dataframe with multiple indexes based on single index

I'm still pretty new to Pandas but I've searched around quite a bit and can't quite find what I'm looking for. 我对Pandas还是很陌生,但是我已经搜索了很多,却找不到我想要的东西。

So here is my problem: 所以这是我的问题:

I have two dataframe - one with mutliple indexes and another with just one index 我有两个数据框-一个具有多个索引,另一个仅具有一个索引

df1=

               value1  value2
ind1 ind2
a      1          1.1     7.1
b      2          2.0     8.0
c      3          3.0     9.0
a      4          4.0    10.0
b      5          5.0    11.0
c      6          6.0    12.0


df2=

           value1  value2
ind1
a           8.0     7.0
b           9.0     8.0
c           3.0     9.0
d           11.0   10.0
e           12.0    11.0
f           1.0    12.0

I would like to index data from df1 based on df2 where value1 > value2 . 我想基于df2从df1索引数据,其中value1 > value2

df2['value1'] > df2['value2']

I know that I can get the data from df2 with 我知道我可以从df2获取数据

df2.loc[df2['value1'] > df2['value2']]

But how would I get data from df1? 但是我如何从df1获取数据? I tried: 我试过了:

df1.loc[df2['value1'] > df2['value2']]

But it fails with 但是它失败了

*** IndexingError: Unalignable boolean Series key provided

Any suggestions will be much appreciated, thank you! 任何建议将不胜感激,谢谢!

Get the indices from df2 and then select df1 on those indices: 从df2获取索引,然后在这些索引上选择df1:

indices = df2.loc[df2['value1'] > df2['value2']]
>>>indices
Index([u'b', u'd', u'e'], dtype='object')
>>>df1.ix[indices]

ind1 ind2   val1    val2
b    2      2.0     8.0
b    5      5.0     11.0

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

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