<p>你可以重新索引一下。你知道吗</p>
<pre><code>from itertools import product
# Get rid of that number in the index, not sure why you'd need it
df.index = df.index.droplevel(-1)
# Add continents to the index
df = df.set_index('continent', append=True)
# Determine product of indices
ids = list(product(df.index.get_level_values(0).unique(), df.index.get_level_values(1).unique()))
# Reindex and fill missing with 0
df = df.reindex(ids).fillna(0).reset_index(level=-1)
</code></pre>
<p><code>df</code>现在是:</p>
<pre><code> continent avg_count_country avg_age
Male Asia 55.0 5.0
Male Africa 65.0 10.0
Male Europe 75.0 8.0
Male America 0.0 0.0
Female Asia 50.0 7.0
Female Africa 60.0 12.0
Female Europe 70.0 0.0
Female America 0.0 0.0
Transgender Asia 30.0 6.0
Transgender Africa 40.0 11.0
Transgender Europe 0.0 0.0
Transgender America 80.0 10.0
</code></pre>
<p>如果你想要另一个数字索引,那么你可以:
<code>df.groupby(df.index).cumcount()</code>对每组中的值进行编号。你知道吗</p>