How to get every nth column in pandas?
slice the columns:
df[df.columns[::2]]
To get every nth column
Example:
In [2]:
cols = ['a1','b1','c1','a2','b2','c2','a3']
df = pd.DataFrame(columns=cols)
df
Out[2]:
Empty DataFrame
Columns: [a1, b1, c1, a2, b2, c2, a3]
Index: []
In [3]:
df[df.columns[::3]]
Out[3]:
Empty DataFrame
Columns: [a1, a2, a3]
Index: []
You can also filter using startswith
:
In [5]:
a = df.columns[df.columns.str.startswith('a')]
df[a]
Out[5]:
Empty DataFrame
Columns: [a1, a2, a3]
Index: []
and do the same for b cols and c cols etc..
You can get a set of all the unique col prefixes using the following:
In [19]:
df.columns.str.extract(r'([a-zA-Z])').unique()
Out[19]:
array(['a', 'b', 'c'], dtype=object)
You can then use these values to filter the columns using startswith
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]
The following should work:
df.ix[:, ::2] - get every second column, beginning with first (here all a's)
df.ix[:, 1::2] - get every second column, beginning with second (b's)
....
I just searched for a solution to the same problem and that solved it.