gpt4 book ai didi

python - 如何在 pandas 中选择一个级别和所有子级别(和项目)?

转载 作者:行者123 更新时间:2023-11-30 22:01:09 24 4
gpt4 key购买 nike

我有一个多级数据框:

year month  Open      High      Low       Close
2018 1 25565.75 27379.45 27652.05 25232.80
2 27334.85 25107.40 27613.50 24781.70
3 25022.35 24263.35 25226.05 23605.60
4 24235.65 25531.60 25617.50 24062.95
5 25607.05 26956.20 27164.55 25469.05
2019 1 27231.40 27720.40 27754.45 26923.75

我正在尝试选择 2018 type (int64) 并将其制作为单独的数据帧。

我已经尝试过:

df[2017]

我收到按键错误

df.loc[pd.IndexSlice[0,'打开']]

这可以让我获得所有开盘价。

df.loc[pd.IndexSlice['年份':,'打开']]

df.loc[pd.IndexSlice['2017','Open']]

它们似乎不起作用。

如何进入关卡?还记得它们是 int64 类型吗?

预期输出:

     month  Open      High      Low       Close
1 25565.75 27379.45 27652.05 25232.80
2 27334.85 25107.40 27613.50 24781.70
3 25022.35 24263.35 25226.05 23605.60
4 24235.65 25531.60 25617.50 24062.95
5 25607.05 26956.20 27164.55 25469.05

此外,如果还有另一个级别,我将如何访问下两个级别的数据?

谢谢

最佳答案

您想要选择索引,因此需要loc:

df = df.loc[2018]

或者使用DataFrame.xs :

df = df.xs(2018)

或者如果想选择第二级中的所有值需要 : :

df = df.loc[pd.IndexSlice[2018,:]]
print (df)
Open High Low Close
month
1 25565.75 27379.45 27652.05 25232.80
2 27334.85 25107.40 27613.50 24781.70
3 25022.35 24263.35 25226.05 23605.60
4 24235.65 25531.60 25617.50 24062.95
5 25607.05 26956.20 27164.55 25469.05

关于python - 如何在 pandas 中选择一个级别和所有子级别(和项目)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54129929/

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