Applying an operation on multiple columns with a fixed column in pandas
<p>I have a dataframe as shown below. The last column shows the sum of values from all the columns i.e. <code>A</code>,<code>B</code>,<code>D</code>,<code>K</code> and <code>T</code>. Please note some of the columns have <code>NaN</code> as well.</p>

<pre><code>word1,A,B,D,K,T,sum
na,,63.0,,,870.0,933.0
sva,,1.0,,3.0,695.0,699.0
a,,102.0,,1.0,493.0,596.0
sa,2.0,487.0,,2.0,15.0,506.0
su,1.0,44.0,,136.0,214.0,395.0
waw,1.0,9.0,,34.0,296.0,340.0
</code></pre>

<p>How can I calculate the entropy for each row? i.e. I should find something like following</p>

<pre><code>df['A']/df['sum']*log(df['A']/df['sum']) + df['B']/df['sum']*log(df['B']/df['sum']) + ...... + df['T']/df['sum']*log(df['T']/df['sum'])
</code></pre>

<p>The condition is that whenever the value inside the <code>log</code> becomes <code>zero</code> or <code>NaN</code>, the whole value should be treated as zero (by definition, the log will return an error as log 0 is undefined).</p>

<p>I am aware of using lambda operation to apply on individual columns. Here I am not able to think for a pure pandas solution where a fixed column <code>sum</code> is applied on different columns <code>A</code>,<code>B</code>,<code>D</code> etc.. Though I can think of a simple loopwise iteration over CSV file with hard-coded column values.</p>

<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> for selecting columns from <code>A</code> to <code>T</code>, then divide by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a> with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html" rel="nofollow"><code>numpy.log</code></a>. Last use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a>:</p>

<pre><code>print (df['A']/df['sum']*np.log(df['A']/df['sum']))
0         NaN
1         NaN
2         NaN
3   -0.021871
4   -0.015136
5   -0.017144
dtype: float64

print (df.ix[:,'A':'T'].div(df['sum'],axis=0)*np.log(df.ix[:,'A':'T'].div(df['sum'],axis=0)))
          A         B   D         K         T
0       NaN -0.181996 NaN       NaN -0.065191
1       NaN -0.009370 NaN -0.023395 -0.005706
2       NaN -0.302110 NaN -0.010722 -0.156942
3 -0.021871 -0.036835 NaN -0.021871 -0.104303
4 -0.015136 -0.244472 NaN -0.367107 -0.332057
5 -0.017144 -0.096134 NaN -0.230259 -0.120651

print((df.ix[:,'A':'T'].div(df['sum'],axis=0)*np.log(df.ix[:,'A':'T'].div(df['sum'],axis=0)))
         .sum(axis=1))
0   -0.247187
1   -0.038471
2   -0.469774
3   -0.184881
4   -0.958774
5   -0.464188
dtype: float64
</code></pre>

python pandas dataframe sum multiple-columns