<p>我想你在找<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">df.pivot</a>。从熊猫文档:</p>
<blockquote>
<p>Reshape data (produce a “pivot” table) based on column values. Uses unique values from specified index / columns to form axes of the resulting DataFrame. This function does not support data aggregation, multiple values will result in a MultiIndex in the columns. See the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html#reshaping" rel="nofollow noreferrer">User Guide</a> for more on reshaping.</p>
</blockquote>
<p>在案例中使用pivot会在索引中生成CustomerID,在列中生成Product:</p>
<pre class="lang-py prettyprint-override"><code>In [4]: df.pivot('CustomerID', 'Product', 'Quantity')
Out[4]:
Product Ball Leash
CustomerID
123 2.0 2.0
456 1.0 NaN
</code></pre>
<p>然后可以使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">^{<cd1>}</a>在剩余的单元格中获取0</p>