问题描述
我正在尝试围绕多级索引。
具体来说,我试图获得满足“任何”标准的所有 0 级指标。 但我一辈子都无法理解如何让它发挥作用。
例如,在下面的数据框中,我们希望所有在“test_variable_2”列中包含“3”的索引
事件名称 | test_variable_1 | test_variable_2 | test_variable_3 | |
---|---|---|---|---|
subject_id | ||||
1 | pre_event | NaN | 3 | 脚 |
1 | intra_event | 15 | NaN | 栏 |
1 | post_event | 30 | NaN | 气 |
2 | pre_event | NaN | 2 | 脚 |
2 | intra_event | 45 | NaN | NaN |
2 | post_event | 60 | NaN | 气 |
3 | pre_event | NaN | 3 | 脚 |
3 | intra_event_1 | 75 | NaN | 栏 |
3 | intra_event_2 | 90 | NaN | NaN |
3 | post_event | 105 | NaN | 气 |
结果应该是:
事件名称 | test_variable_1 | test_variable_2 | test_variable_3 | |
---|---|---|---|---|
subject_id | ||||
1 | pre_event | NaN | 3 | 脚 |
1 | intra_event | 15 | NaN | 栏 |
1 | post_event | 30 | NaN | 气 |
3 | pre_event | NaN | 3 | 脚 |
3 | intra_event_1 | 75 | NaN | 栏 |
3 | intra_event_2 | 90 | NaN | NaN |
3 | post_event | 105 | NaN | 气 |
我考虑过使用 .groupby 函数,但我担心我会丢失一些包含多个值的测试变量。 到目前为止,我的解决方案是选择填充布尔掩码的索引,然后删除所有其他索引,但这看起来很麻烦,而且不是很熊猫式。
我确信有一种方法可以利用多级索引。任何指向正确方向的指针都会有所帮助。
解决方法
试试
out = df.loc[df.index.isin(df.index[df['test_variable_2'].eq(3)])]
Out[529]:
event_name test_variable_1 test_variable_2 test_variable_3
subject_id
1 pre_event NaN 3.0 foo
1 intra_event 15.0 NaN bar
1 post_event 30.0 NaN fum
3 pre_event NaN 3.0 foo
3 intra_event_1 75.0 NaN bar
3 intra_event_2 90.0 NaN NaN
3 post_event 105.0 NaN fum
,
使用groupby().transform
:
df[df['test_variable_2'].eq(3).groupby(level=0).transform('any')]
或者您可以只对有效索引使用 unique
:
df.loc[df[df.test_variable_2.eq(3)].index.unique()]
输出:
event_name test_variable_1 test_variable_2 test_variable_3
subject_id
1 pre_event NaN 3.0 foo
1 intra_event 15.0 NaN bar
1 post_event 30.0 NaN fum
3 pre_event NaN 3.0 foo
3 intra_event_1 75.0 NaN bar
3 intra_event_2 90.0 NaN NaN
3 post_event 105.0 NaN fum
,
可以将 .loc
链接到 .eq
请注意,这仅适用于唯一索引值,按照@Quang Hoang 的建议添加 unique
子句会更安全。
df.loc[df.loc[df['test_variable_2'].eq(3)].index]
event_name test_variable_1 test_variable_2 test_variable_3
subject_id
1 pre_event NaN 3.0 foo
1 intra_event 15.0 NaN bar
1 post_event 30.0 NaN fum
3 pre_event NaN 3.0 foo
3 intra_event_1 75.0 NaN bar
3 intra_event_2 90.0 NaN NaN
3 post_event 105.0 NaN fum
我也不认为你有一个多索引,但如果你有,你可以用 index
替换 .index.get_level_values(0)
以获得级别 0
值,然后使用 {{1 }}
假设您的有效索引已分配给名为 isin
的变量
valid_indexes