How to get every nth column in pandas?

Viewed 42953

I have a dataframe which looks like this:

    a1    b1    c1    a2    b2    c2    a3    ...
x   1.2   1.3   1.2   ...   ...   ...   ...
y   1.4   1.2   ...   ...   ...   ...   ...
z   ...

What I want is grouping by every nth column. In other words, I want a dataframe with all the as, one with bs and one with cs

    a1     a2     a4
x   1.2    ...    ...
y
z

In another SO question I saw that is possibile to do df.iloc[::5,:], for example, to get every 5th raw. I could do of course df.iloc[:,::3] to get the c cols but it doesn't work for getting a and b.

Any ideas?

3 Answers

In current version (0.24), this works:

Getting your 'a' columns:

df.iloc[:, ::3]

getting your 'b' columns:

df.iloc[:, 1::3]

getting your 'c' columns:

df.iloc[:, 2::3]
Related