Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's one way using a groupby to B level of the DataFrame:</p> <pre><code>In [11]: p Out[11]: V1 V2 B C c e 1870 1911 f 1887 816 d e 230 25 f 1890 1055 In [12]: g = p.groupby(level='B') </code></pre> <p>and take the percentage of each of the V2s in each group:</p> <pre><code>In [13]: g['V2'].apply(lambda s: s.astype(float) / s.sum()) Out[13]: B C c e 0.700770 f 0.299230 d e 0.023148 f 0.976852 dtype: float64 </code></pre> <p>Finally, assign this as a column:</p> <pre><code>In [14]: p['PercentOfB'] = g['V2'].apply(lambda s: s.astype(float) / s.sum()) In [15]: p Out[15]: V1 V2 PercentOfB B C c e 1870 1911 0.700770 f 1887 816 0.299230 d e 230 25 0.023148 f 1890 1055 0.976852 </code></pre> <p>To expand a little on what's going on here, during the apply the function is called on each group (in this case there are two, one for B='c' and one for B='d'), here's the c group:</p> <pre><code>In [21]: c Out[21]: B C c e 1911 f 816 Name: c, dtype: int64 </code></pre> <p>and the interested result is to divide through by the total:</p> <pre><code>In [22]: c.sum() Out[22]: 2727 </code></pre> <p>Unfortunately in python 2, integer division isn't "proper":</p> <pre><code>In [23]: c / c.sum() Out[23]: B C c e 0 f 0 Name: c, dtype: int64 </code></pre> <p>So we need to fix it by making them floats, usually I use <code>astype(float)</code> or <code>* 1.0</code> to force this:</p> <pre><code>In [24]: c.astype(float) / c.sum() Out[24]: B C c e 0.70077 f 0.29923 Name: c, dtype: float64 </code></pre> <p>Apply then outputs this together with the B='d' group to get the desired result.</p> <p><em>Note: Regarding how I got c, as I find this a very useful trick to writing applies.</em></p> <p><em>I created a dummy function and an empty list, and applied it to the groupby:</em></p> <pre><code>a = [] def f(x): a.append(x) return x g['v2'].apply(f) c = a[0] </code></pre> <p><em>Then I played with that 'til I got what I want.</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload