<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html#pandas.DataFrame.set_index" rel="nofollow noreferrer">set_index</a>、<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer">crosstab</a>和<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer">reindex</a>的组合可以“取消”数据帧,并处理数据帧中存在的空值:</p>
<pre><code>#set aside required multiindex of country, state, restaurant, stars, and reviews
ind = df.set_index(['COUNTRY','STATE','RESTAURANT','STARS','REVIEWS']).index
#get frequency count for Pizza and Spicy
res = pd.crosstab([df.COUNTRY,df.STATE,df.RESTAURANT,df.STARS,df.REVIEWS],df.CATEGORY)
#reindex frequency dataframe with ind
res = res.reindex(ind,fill_value=0).drop_duplicates()
res
CATEGORY Pizza Spicy
COUNTRY STATE RESTAURANT STARS REVIEWS
US Texas Texas Chicken 4.1 1,157 0 1
Ohio Mamas Shop 3.6 700 0 0
Pizza Hut 4.5 855 1 0
</code></pre>