Add prefix to specific columns of Dataframe
<p>I've a DataFrame like that :</p>

<pre><code>col1   col2   col3   col4   col5   col6   col7   col8
0      5345   rrf    rrf    rrf    rrf    rrf    rrf
1      2527   erfr   erfr   erfr   erfr   erfr   erfr
2      2727   f      f      f      f      f      f
</code></pre>

<p>I would like to rename all columns but not <strong>col1</strong> and <strong>col2</strong>.</p>

<p>So I tried to make a loop</p>

<pre><code>print(df.columns)
    for col in df.columns:
        if col != 'col1' and col != 'col2':
            col.rename = str(col) + '_x'
</code></pre>

<p>But it's not very efficient...it doesn't work !</p>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>str.contains</code></a> with a regex pattern to filter the cols of interest, then using <code>zip</code> construct a dict and pass this as the arg to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow"><code>rename</code></a>:</p>

<pre><code>In [94]:
cols = df.columns[~df.columns.str.contains('col1|col2')]
df.rename(columns = dict(zip(cols, cols + '_x')), inplace=True)
df

Out[94]:
   col1  col2 col3_x col4_x col5_x col6_x col7_x col8_x
0     0  5345    rrf    rrf    rrf    rrf    rrf    rrf
1     1  2527   erfr   erfr   erfr   erfr   erfr   erfr
2     2  2727      f      f      f      f      f      f
</code></pre>

<p>So here using <code>str.contains</code> to filter the columns will return the columns that don't match so the column order is irrelevant</p>

python pandas