gpt4 book ai didi

python - Pandas MultiIndex 获取所有一个 0 级列和一个特定列

转载 作者:行者123 更新时间:2023-12-05 01:03:59 25 4
gpt4 key购买 nike

我有一个 pandas DataFrame,列上有一个 MultiIndex,我想访问 bar 的所有列以及 baz 下的一个附加列> - 我怎样才能做到这一点?

输入:

import numpy as np
import pandas as pd

np.random.seed(123)
iterables = [["bar", "baz", "foo", "qux"], ["one", "two"]]
idx = pd.MultiIndex.from_product(iterables, names=["first", "second"])
df = pd.DataFrame(np.random.randn(4, 8), columns=idx)

first bar baz foo qux
second one two one two one two one two
0 -1.085631 0.997345 0.282978 -1.506295 -0.578600 1.651437 -2.426679 -0.428913
1 1.265936 -0.866740 -0.678886 -0.094709 1.491390 -0.638902 -0.443982 -0.434351
2 2.205930 2.186786 1.004054 0.386186 0.737369 1.490732 -0.935834 1.175829
3 -1.253881 -0.637752 0.907105 -1.428681 -0.140069 -0.861755 -0.255619 -2.798589

预期输出:

first        bar                 baz
second one two two
0 -1.085631 0.997345 -1.506295
1 1.265936 -0.866740 -0.094709
2 2.205930 2.186786 0.386186
3 -1.253881 -0.637752 -1.428681

我可以指定特定的列,例如 df.loc[:, [("bar", "one"), ("bar", "two"), ("baz", "two")]] 但我似乎不能只为一个顶级指定任意数字,例如 df.loc[:, ["bar", ("baz", "two")]]

最佳答案

iloc解决方案

ix = df.columns.get_loc
df.iloc[:, np.r_[ix('bar'), ix(('baz', 'two'))]]

first        bar                 baz
second one two two
0 -1.085631 0.997345 -1.506295
1 1.265936 -0.866740 -0.094709
2 2.205930 2.186786 0.386186
3 -1.253881 -0.637752 -1.428681

关于python - Pandas MultiIndex 获取所有一个 0 级列和一个特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73040004/

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