gpt4 book ai didi

python - 从 pandas MultiIndex 中选择列

转载 作者:IT老高 更新时间:2023-10-28 21:06:22 27 4
gpt4 key购买 nike

我有带有 MultiIndex 列的 DataFrame,如下所示:

# sample data
col = pd.MultiIndex.from_arrays([['one', 'one', 'one', 'two', 'two', 'two'],
['a', 'b', 'c', 'a', 'b', 'c']])
data = pd.DataFrame(np.random.randn(4, 6), columns=col)
data

sample data

从第二级只选择特定列(例如 ['a', 'c'],不是范围)的正确、简单的方法是什么?

目前我正在这样做:

import itertools
tuples = [i for i in itertools.product(['one', 'two'], ['a', 'c'])]
new_index = pd.MultiIndex.from_tuples(tuples)
print(new_index)
data.reindex_axis(new_index, axis=1)

expected result

然而,这感觉不是一个好的解决方案,因为我必须淘汰 itertools,手动构建另一个 MultiIndex,然后重新索引(而且我的实际代码更加困惑,因为该列列表不是那么容易获取)。我很确定必须有一些 ixxs 方法来执行此操作,但我尝试的所有操作都导致了错误。

最佳答案

最直接的方法是使用.loc:

>>> data.loc[:, (['one', 'two'], ['a', 'b'])]


one two
a b a b
0 0.4 -0.6 -0.7 0.9
1 0.1 0.4 0.5 -0.3
2 0.7 -1.6 0.7 -0.8
3 -0.9 2.6 1.9 0.6

记住 []() 在处理 MultiIndex 对象时具有特殊含义:

(...) a tuple is interpreted as one multi-level key

(...) a list is used to specify several keys [on the same level]

(...) a tuple of lists refer to several values within a level

当我们编写 (['one', 'two'], ['a', 'b']) 时,元组中的第一个列表指定了我们想要的所有值MultiIndex 的级别。元组中的第二个列表指定了我们想要的第二级 MultiIndex 中的所有值。

编辑 1: 另一种可能性是使用 slice(None) 来指定我们想要第一级的任何内容(类似于使用 进行切片: 在列表中)。然后指定我们想要的第二层的哪些列。

>>> data.loc[:, (slice(None), ["a", "b"])]

one two
a b a b
0 0.4 -0.6 -0.7 0.9
1 0.1 0.4 0.5 -0.3
2 0.7 -1.6 0.7 -0.8
3 -0.9 2.6 1.9 0.6

如果语法 slice(None) 确实对您有吸引力,那么另一种可能性是使用 pd.IndexSlice,它有助于对具有更精细索引的帧进行切片。

>>> data.loc[:, pd.IndexSlice[:, ["a", "b"]]]

one two
a b a b
0 0.4 -0.6 -0.7 0.9
1 0.1 0.4 0.5 -0.3
2 0.7 -1.6 0.7 -0.8
3 -0.9 2.6 1.9 0.6

当使用 pd.IndexSlice 时,我们可以像往常一样使用 : 对帧进行切片。

来源:MultiIndex / Advanced Indexing , How to use slice(None)

关于python - 从 pandas MultiIndex 中选择列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18470323/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com