Note that there are some explanatory texts on larger screens.

plurals
  1. POPivoting pandas DataFrame -- AssertionError: Index length did not match values
    primarykey
    data
    text
    <p>I have a <em>pandas.DataFrame</em> that won't pivot the way I expect. While <code>pivot_table</code> properly arranges everything, the fact that it uses aggregate functions to get there is off-putting. In addition, <code>pivot_table</code> seems to return an unnecessarily complex object rather than a flat data frame.</p> <p>Consider the following example</p> <pre><code>import pandas as pd df = pd.DataFrame({'firstname':['Jon']*3+['Amy']*2, 'lastname':['Cho']*3+['Frond']*2, 'vehicle':['bike', 'car', 'plane','bike','plane'], 'weight':[81.003]*3+[65.6886]*2, 'speed':[29.022, 95.1144, 302.952, 27.101, 344.2],}) df.set_index(['firstname','lastname','weight']) print('------ Unnecessary pivot_table does averaging ------') print(pd.pivot_table(df, values='speed', rows='firstname','lastname','weight'], cols='vehicle')) print('------ pivot method dies ------') print(df.pivot( index=['firstname','lastname','weight'], columns='vehicle', values='speed')) </code></pre> <p>The <code>pivot_table</code> results are</p> <pre><code>vehicle bike car plane firstname lastname weight Amy Frond 65.6886 27.101 NaN 344.200 Jon Cho 81.0030 29.022 95.1144 302.952 </code></pre> <p>Is there a way to get <code>pivot</code> to give essentially the same output as the <code>pivot_table</code> command did (but hopefully flatter and neater)? Failing that, how do I flatten the output of <code>pivot_table</code>? What I want as output is something more like this:</p> <pre><code>firstname lastname weight bike car plane Amy Frond 65.6886 27.101 NaN 344.200 Jon Cho 81.0030 29.022 95.1144 302.952 </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.
 

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