efficiently replace values from a column to another column Pandas DataFrame
<p>I have a Pandas DataFrame like the following one: </p>

<pre><code>   col1 col2 col3
1   0.2  0.3  0.3
2   0.2  0.3  0.3
3     0  0.4  0.4
4     0    0  0.3
5     0    0    0
6   0.1  0.4  0.4
</code></pre>

<p>I want to replace the <code>col1</code> values with the values in the second column (<code>col2</code>) only if <code>col1</code> values are equal to 0, and after (for the zero values remaining),  do it again but with the third column (<code>col3</code>). The Desired Result is the next one:</p>

<pre><code>   col1 col2 col3
1   0.2  0.3  0.3
2   0.2  0.3  0.3
3   0.4  0.4  0.4
4   0.3    0  0.3
5     0    0    0
6   0.1  0.4  0.4
</code></pre>

<p>I did it using the <code>pd.replace</code> function, but it seems too slow.. I think must be a faster way to accomplish that. </p>

<pre><code>df.col1.replace(0,df.col2,inplace=True)
df.col1.replace(0,df.col3,inplace=True)
</code></pre>

<p>is there a faster way to do that?, using some other function instead of the <code>pd.replace</code> function?, maybe slicing the <code>df.col1</code> ?</p>

<p>PS1. Additional info: the original goal of the problem is to replace the zero values (in <code>col1</code>) with the statistic mode of some groups of ids. That is why I have <code>col2</code>(best mode, first option of replacement) and <code>col3</code>(last mode, still functional but not so desirable as <code>col2</code>). </p>

<p>I'm not sure if it's faster, but you're right that you can slice the dataframe to get your desired result.</p>

<pre><code>df.col1[df.col1 == 0] = df.col2
df.col1[df.col1 == 0] = df.col3
print(df)
</code></pre>

<p>Output:</p>

<pre><code>   col1  col2  col3
0   0.2   0.3   0.3
1   0.2   0.3   0.3
2   0.4   0.4   0.4
3   0.3   0.0   0.3
4   0.0   0.0   0.0
5   0.1   0.4   0.4
</code></pre>

<p>Alternatively if you want it to be more terse (though I don't know if it's faster) you can combine what you did with what I did.</p>

<pre><code>df.col1[df.col1 == 0] = df.col2.replace(0, df.col3)
print(df)
</code></pre>

<p>Output:</p>

<pre><code>   col1  col2  col3
0   0.2   0.3   0.3
1   0.2   0.3   0.3
2   0.4   0.4   0.4
3   0.3   0.0   0.3
4   0.0   0.0   0.0
5   0.1   0.4   0.4
</code></pre>

python pandas replace dataframe