pandas row operation to keep only the right most non zero value per row
<p>How to keep the right most number in each row in a dataframe?</p>

<pre><code>a = [[1, 2, 0], [1, 3, 0], [1, 0, 0]]
df = pd.DataFrame(a, columns=['col1','col2','col3'])
df

      col1  col2    col3
row0    1   2       NaN
row1    1   3       0
row2    1   0       0
</code></pre>

<p>Then after transformation</p>

<pre><code>      col1  col2    col3
row0    0   2       0
row1    0   3       0
row2    1   0       0
</code></pre>

<p>Based on the suggestion by <a href="http://stackoverflow.com/users/3293881/divakar">divakar</a> I've come up with the following:</p>

<pre><code>import pandas as pd
a = [[1, 2, 0, None], 
     [1, 3, 0,0], 
     [1, 0, 0,0], 
     [1, 0, 0,0], 
     [1, 0, 0,0], 
     [0, 0, 0,1]]

df = pd.DataFrame(a, columns=['col1','col2','col3','col4'])
df.fillna(value=0,inplace=True) # Get rid of non numeric items
a

[[1, 2, 0, None],
 [1, 3, 0, 0],
 [1, 0, 0, 0],
 [1, 0, 0, 0],
 [1, 0, 0, 0],
 [0, 0, 0, 1]]

# Return index of first occurrence of maximum over requested axis.
# 0 or 'index' for row-wise, 1 or 'columns' for column-wise
df.idxmax(1)

0    col2
1    col2
2    col1
3    col1
4    col1
5    col4
dtype: object
</code></pre>

<p>Create a matrix to mask values</p>

<pre><code>numberOfRows = df.shape[0]
df_mask= pd.DataFrame(columns=df.columns,index=np.arange(0, numberOfRows))
df_test.fillna(value=0,inplace=True) # Get rid of non numeric items

# Add mask entries
for row,col in enumerate(df.idxmax(1)):
   df_mask.loc[row,col] = 1

df_result=df*df_mask
df_result

col1    col2    col3    col4
0   0   2   0   0.0
1   0   3   0   0.0
2   1   0   0   0.0
3   1   0   0   0.0
4   1   0   0   0.0
5   0   0   0   1.0
</code></pre>

<p>You can fill null values "from the left", and then take the values of the resulting last column:</p>

<pre><code>In [49]: df.fillna(axis=0, method='bfill')['col3']
Out[49]: 
0    0.0
1    0.0
2    0.0
Name: col3, dtype: float64
</code></pre>

<p><strong>Full Example</strong></p>

<pre><code>In [50]: a = [[1, 2, None], [1, 3, 0], [0, 0, 0]]

In [51]: df = pd.DataFrame(a, columns=['col1','col2','col3'])

In [52]: df.fillna(axis=0, method='bfill')['col3']
Out[52]: 
0    0.0
1    0.0
2    0.0
Name: col3, dtype: float64
</code></pre>

python pandas dataframe