Python: replace data frame values based on column name and conditional
<p>Letâs say we have a data frame with 6 columns. For a subset of 3 of those columns we want to change instances of 3 to 1. Can you suggest an elegant way to do so?
Simply writing a line like:</p>

<pre><code>df['A'][df.A == 3] = 1 
</code></pre>

<p>is inefficient in my real data as the dimensions are much larger (like changing 50 out of 200 variables). </p>

<p>Perhaps we could work on this example:</p>

<pre><code>df = pd.DataFrame(np.random.randint(0,10,size=(100, 6)), columns=list('ABCDEF'))
</code></pre>

<p>Where we want to change values of 3 to 1 in columns A, B, and C. Thanks.</p>

<p>You can loop through the subset of columns and use <code>loc</code> for assignment.</p>

<pre><code>subset cols = ['A', 'B', 'C']  # For example.
for col in subset_cols:
    df.loc[df[col] == 3, col] = 1
</code></pre>

python dataframe