Pandas select columns using slicing and integer index
<p>I am trying to select columns 2 and 4: (column 4 till the end):</p>

<pre><code>df3.iloc[:, [2, 4:]]
</code></pre>

<blockquote>
  <p>File "", line 1<br>
  df3.iloc[:, [2, 4:]]<br>
  ___________^<br>
  SyntaxError: invalid syntax  </p>
</blockquote>

<p>I get an error message obviously. There are many columns after col 4 so writing something like this does not feel right: [2, 4, 5, 6, 7, ...]</p>

<p>Is there any other quick way of doing this?</p>

<p>You can use <code>range</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html" rel="nofollow"><code>shape</code></a>:</p>

<pre><code>df3 = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df3)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

cols = ([2] + list(range(4,df3.shape[1])))
print (cols)
[2, 4, 5]

print (df3.iloc[:,cols])
   C  E  F
0  7  5  7
1  8  3  4
2  9  6  3
</code></pre>

<p>Another solution with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow"><code>numpy.r_</code></a>:</p>

<pre><code>cols1 = np.r_[2, np.arange(4,df3.shape[1])]
print (cols1)
[2 4 5]

print (df3.iloc[:,cols1])
   C  E  F
0  7  5  7
1  8  3  4
2  9  6  3
</code></pre>

python pandas indexing dataframe slice