<p>首先,这不是一个透视表作业,而是一个<code>groupby</code>作业。</p>
<p>数据透视表用于在未设置索引(请参见<a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow">this doc article</a>)、<code>stack</code>和<code>unstack</code>时重新调整数据的形状,用于在设置索引时重新调整数据的形状,而<code>groupby</code>用于聚合(这是什么)和<a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">split-apply-combine</a>操作。</p>
<p>以下是如何使用<code>groupby</code>获取患者计数:</p>
<pre><code>>>> patient_count = df.groupby(['hospital', 'region']).count()
>>> print patient_count
patient
hospital region
h1 r1 3
h2 r1 4
h3 r1 5
h4 r2 6
h5 r2 7
h6 r2 8
h7 r3 9
h8 r3 10
h9 r3 11
</code></pre>
<p>要选择多索引中的某些行,我通常使用<code>ix</code>,如下所示:</p>
<pre><code>>>> h7 = patient_count.ix['h7']
>>> print h7
patient
region
r3 9
</code></pre>
<p>现在您可以使用<code>get_level_values</code></p>
<pre><code>>>> h7.index.values[0]
'r3'
</code></pre>
<p>或者,如果您不想要多索引版本(而且出于您的目的,您可能不想要),您可以执行以下操作:</p>
<pre><code>>>> patient_count = patient_count.reset_index()
</code></pre>
<p>它允许您查找哪个地区的医院<code>h7</code>,如下所示:</p>
<pre><code>>>> patient_count.region[patient_count.hospital == 'h7']
6 r3
Name: region, dtype: object
</code></pre>
<p>如果你只想<code>r3</code>,你可以:</p>
<pre><code>>>> patient_count.region[patient_count.hospital == 'h7'].values[0]
'r3'
</code></pre>
<p>请注意,<code>reset_index</code>不会在适当的位置发生,这使得它非常适合链接这样的方法:</p>
<pre><code>>>> patient_count.ix['h7'].reset_index().region[0]
'r3'
</code></pre>