Apply a weight formula over a Dataframe using Numpy
<p>I have a Dataframe and am looking to divide the float value of a cell by the sum of the row where it resides. For this I use a numpy formula. This therefore would give me a weight for that cell for that row. I have this dataframe <code>df1</code>:</p>

<pre class="lang-none prettyprint-override"><code>                           AA          AB             AC           AD  
2005-01-02 23:55:00      "EQUITY"    "EQUITY"      "EQUITY"     "EQUITY"   
2005-01-03 00:00:00        32.32      19.5299        32.32      31.0455   
2005-01-04 00:00:00      31.9075      19.4487      31.9075      30.3755   
2005-01-05 00:00:00      31.6151      19.5799      31.6151       29.971   
2005-01-06 00:00:00      31.1426      19.7174      31.1426      29.9647  
</code></pre>

<p>I have tried the following so far:</p>

<pre><code>import numpy as np

def foo_bar(x):
    if type(x) is not str:
        return x / np.sum(df1, axis=1)
    else:
        return

df = df_numeric.apply(np.vectorize(foo_bar))
</code></pre>

<p>It seems the sum part of my formula is not properly written as I get the following error:</p>

<pre class="lang-none prettyprint-override"><code>                           AA          AB             AC           AD  
ValueError: ('setting an array element with a sequence.', 'occurred at index AA')
</code></pre>

<p>Try the following bit of code, which uses pandas features instead of an explicit function.</p>

<p>The function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow">div</a> performs an element wise division. You feed the total sums as a series to that function, and use the row index of your original element to select the appropriate value for division.</p>

<pre><code>import numpy as np
import pandas as pd

data = pd.DataFrame(np.arange(12).reshape((3, 4)),columns=['A', 'B', 'C', 'D']) 

data['Total'] = data.sum(axis=1)

data_new= data.iloc[:, :-1].div(data["Total"], axis=0)

print data  
print data_new  
</code></pre>

<p>Result:</p>

<pre><code>   A  B   C   D  Total
0  0  1   2   3      6
1  4  5   6   7     22
2  8  9  10  11     38
          A         B         C         D
0  0.000000  0.166667  0.333333  0.500000
1  0.181818  0.227273  0.272727  0.318182
2  0.210526  0.236842  0.263158  0.289474
</code></pre>

python pandas numpy dataframe