gpt4 book ai didi

python - 选择和切片属于 PeriodIndex 的列

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:16 26 4
gpt4 key购买 nike

我有一个 DataFrame,其中列是按月的 PeriodIndex,如下所示:

df = pd.DataFrame(np.random.randn(3,4), index = np.arange(3), columns = pd.period_range('2015-01', freq = 'M', periods = 4))


2015-01 2015-02 2015-03 2015-04
0 -1.459943 -1.572013 2.977714 -0.067696
1 -1.545259 -0.570757 0.133756 -1.231192
2 0.498197 -0.555625 0.174545 0.371475

我可以选择列的子集,如下所示:

testdf[[pd.Period('2015-01'),pd.Period('2015-03')]]

2015-01 2015-03
0 -1.459943 2.977714
1 -1.545259 0.133756
2 0.498197 0.174545

但是,当谈到切片以获取例如从“2015-01”到“2015-03”的所有月份时,我对所需的语法感到困惑。我尝试了各种迭代都没有运气。

例如:

df[pd.Period('2015-01'):pd.Period('2015-03')]
df['2015-01':'2015-03']

所有这些都不起作用。

如何对这个 PeriodIndex 进行切片?

最佳答案

使用 .ix 为列选择 arg 传递切片:

In [9]:
df.ix[:,pd.Period('2015-01'):pd.Period('2015-03')]

Out[9]:
2015-01 2015-02 2015-03
0 0.046028 -0.298445 0.908185
1 -0.955049 -1.420290 1.632564
2 0.848906 0.089553 0.551265

关于python - 选择和切片属于 PeriodIndex 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36082934/

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