Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Suppose you start with this data:</p> <pre><code>df = pd.DataFrame({'ID': ('STRSUB BOTDWG'.split())*4, 'Days Late': [60, 60, 50, 50, 20, 20, 10, 10], 'quantity': [56, 20, 60, 67, 74, 87, 40, 34]}) # Days Late ID quantity # 0 60 STRSUB 56 # 1 60 BOTDWG 20 # 2 50 STRSUB 60 # 3 50 BOTDWG 67 # 4 20 STRSUB 74 # 5 20 BOTDWG 87 # 6 10 STRSUB 40 # 7 10 BOTDWG 34 </code></pre> <p>Then you can find the status category using <code>pd.cut</code>. Note that by default, <code>pd.cut</code> splits the Series <code>df['Days Late']</code> into categories which are <em>half-open</em> intervals, <code>(-1, 14], (14, 35], (35, 56], (56, 365]</code>:</p> <pre><code>df['status'] = pd.cut(df['Days Late'], bins=[-1, 14, 35, 56, 365], labels=False) labels = np.array('White Yellow Amber Red'.split()) df['status'] = labels[df['status']] del df['Days Late'] print(df) # ID quantity status # 0 STRSUB 56 Red # 1 BOTDWG 20 Red # 2 STRSUB 60 Amber # 3 BOTDWG 67 Amber # 4 STRSUB 74 Yellow # 5 BOTDWG 87 Yellow # 6 STRSUB 40 White # 7 BOTDWG 34 White </code></pre> <p>Now use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="noreferrer"><code>pivot</code></a> to get the DataFrame in the desired form:</p> <pre><code>df = df.pivot(index='ID', columns='status', values='quantity') </code></pre> <p>and use <code>reindex</code> to obtain the desired order for the rows and columns:</p> <pre><code>df = df.reindex(columns=labels[::-1], index=df.index[::-1]) </code></pre> <hr> <p>Thus, </p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'ID': ('STRSUB BOTDWG'.split())*4, 'Days Late': [60, 60, 50, 50, 20, 20, 10, 10], 'quantity': [56, 20, 60, 67, 74, 87, 40, 34]}) df['status'] = pd.cut(df['Days Late'], bins=[-1, 14, 35, 56, 365], labels=False) labels = np.array('White Yellow Amber Red'.split()) df['status'] = labels[df['status']] del df['Days Late'] df = df.pivot(index='ID', columns='status', values='quantity') df = df.reindex(columns=labels[::-1], index=df.index[::-1]) print(df) </code></pre> <p>yields</p> <pre><code> Red Amber Yellow White ID STRSUB 56 60 74 40 BOTDWG 20 67 87 34 </code></pre>
    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