Select and split columns that are periods

I have a DataFrame where the columns are PeriodIndex by month as follows:

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

I can select a subset of columns as follows:

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

However, when it comes to slicing, to get, for example, all the months from “2015-01” to “2015-03”, I don’t understand how the syntax is needed. I tried all kinds of iterations without any luck.

For instance:

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

All of which do not work.

How can I cut this PeriodIndex?

+4
source share
1 answer

Use .ixto pass the slice for the column select argument:

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
+3
source

All Articles