[英]Filter MultiIndex DataFrame by level values
我有一個帶有DataFrame
索引和列的 DataFrame。 我想 select 這個DataFrame
的子集,其中級別 0 的索引不在給定列表中(所以我想排除級別 0 的值不屬於列表的行)並且級別 1 的列不在給定的列表中列表(因此排除級別 1 的值不屬於給定列表的列。我該怎么做?
這是一種方法:
import numpy as np
import pandas as pd
# Setup
index = pd.MultiIndex.from_product(
[["bar", "baz", "foo", "qux"], ["one", "two"]], names=["first", "second"]
)
df = pd.DataFrame(np.random.randn(6, 6), index=index[:6], columns=index[:6])
print(df)
# Output
first bar baz foo
second one two one two one two
first second
bar one -0.970334 0.434532 1.277209 -1.622681 0.385986 0.894817
two 2.037842 0.388206 -1.897472 0.291751 -0.860631 -0.743974
baz one 1.483088 -0.797434 0.421217 0.911051 0.645517 0.643298
two -0.154445 -0.769389 -0.287669 -0.602577 1.064863 0.013943
foo one 0.023713 0.336001 0.821779 0.183035 0.144324 -1.297155
two -1.305088 -3.731492 0.060215 -1.280722 -1.498417 2.103376
# Select level 0 index found in `list1` and level 1 columns found in `list2`:
```python
list1 = ["bar", "foo"]
list2 = ["one"]
new_df = df.loc[
(
[row for row in df.index.get_level_values(0).unique() if row in list1],
df.index.get_level_values(1).unique(),
),
(
df.columns.get_level_values(0).unique(),
[col for col in df.columns.get_level_values(1).unique() if col in list2],
),
]
print(new_df)
# Output
first bar baz foo
second one one one
first second
bar one -0.970334 1.277209 0.385986
two 2.037842 -1.897472 -0.860631
foo one 0.023713 0.821779 0.144324
two -1.305088 0.060215 -1.498417
您可以在 Pandas 文檔中了解有關MultiIndexing
的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.