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>approach using <code>pd.DataFrame.where</code> and <code>pd.DataFrame.bfill</code></p>

<pre><code>df['col1'] = df.where(df.ne(0), np.nan).bfill(axis=1).col1.fillna(0)
df
</code></pre>

<p><a href="http://i.stack.imgur.com/SeDin.png" rel="nofollow"><img src="http://i.stack.imgur.com/SeDin.png" alt="enter image description here"></a></p>

<p>Another approach using <code>np.argmax</code></p>

<pre><code>def pir2(df):
    slc = (df.values != 0).argmax(axis=1)
    return df.values[np.arange(slc.shape[0]), slc]
</code></pre>

<p>I know there is a better way to use <code>numpy</code> to slice.  I just can't think of it at the moment.</p>

python pandas replace dataframe