简体   繁体   English

按条件选择熊猫多索引数据框中的行和子行

[英]Select rows and subrows in pandas multiindex dataframe by condition

I have a multi-indexed dataframe which contains some NaN values inside its index and rows. 我有一个多索引的数据框,它的索引和行中包含一些NaN值。

In:

import pandas as pd
import numpy as np

row1 = {'index1' : 'abc', 'col1' : 'some_value', 'col3' : True}
row2 = {'index2' : 'xyz', 'col2' : 'other_value', 'col3' : np.nan}
row3 = {'index1' : 'def', 'col1' : 'different_value', 'col3' : False}
row4 = {'index2' : 'uvw', 'col2' : 'same_value', 'col3' : np.nan}
df = pd.DataFrame([row1, row2, row3, row4])

df.set_index(['index1', 'index2'], inplace=True)

print(df)

Out:

                          col1         col2   col3
index1 index2                                     
abc    NaN          some_value          NaN   True
NaN    xyz                 NaN  other_value    NaN
def    NaN     different_value          NaN  False
NaN    uvw                 NaN   same_value    NaN

Is there a possibility to get a subset of that dataframe by the condition col3 == True which also includes all "subrows" of the row where that condition holds? 是否有可能通过条件col3 == True获得该数据帧的子集,该条件还包括该条件所在行的所有“子行”?

When I go for 当我去

print(df[df.col3 == True])

I get 我懂了

                     col1 col2  col3
index1 index2                       
abc    NaN     some_value  NaN  True

which is the row where the condition holds. 条件所在的行。 However, what I am looking for is 但是,我正在寻找的是

                     col1         col2  col3
index1 index2                       
abc    NaN     some_value         NaN   True
NaN    xyz            NaN  other value  NaN    

, including the row which does not have the True value itself but is a "subrow" of the row with index1 == abc . ,包括本身没有True值但是index1 == abc的行的“子行”的行。

Is that possible? 那可能吗? Or is the dataframe messed up and should be structured in a different way? 还是数据帧搞砸了,应该以其他方式构造?

A simple solution would be to just use a condition on the padded col3 where the NaNs are replaced with the value of the row they belong to. 一个简单的解决方案是仅在填充的col3上使用一个条件,其中将NaNs替换为它们所属的行的值。 For example: 例如:

>>> df['col3'].fillna(method='pad')

index1  index2
abc     NaN        True
NaN     xyz        True
def     NaN       False
NaN     uvw       False
Name: col3, dtype: bool

Now you can apply the condition like this: 现在,您可以应用以下条件:

>>> df[df['col3'].fillna(method='pad')]

                col1       col2         col3
index1  index2          
abc     NaN     some_value NaN          True
NaN     xyz     NaN        other_value  NaN

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

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