<p>问题2:<em>为什么<code>df1['size']</code>有<code>object</code>的数据类型?</em></p>
<p><code>groupby/transform</code>返回一个带有<a href="https://github.com/pydata/pandas/blob/master/pandas/core/groupby.py#L2463" rel="nofollow">dtype for each column which is compatible</a>的数据帧,其中包含原始列的数据类型和转换结果。由于<code>Name</code>有dtype对象</p>
<pre><code>df1.groupby(['City']).transform(np.size)
</code></pre>
<p>也转换为dtype对象。在</p>
<p>我不知道为什么<code>transform</code>是这样编码的;可能有一些用例要求这样做以确保某种意义上的正确性。在</p>
<hr/>
<p>问题1&3:<em>为什么我得到<code>ValueError: Length mismatch</code>以及如何避免它</p>
<p>在被分组的列中可能有nan。例如,假设我们将<code>City</code>中的一个值更改为<code>NaN</code>:</p>
^{pr2}$
<p>那么</p>
<pre><code>In [86]: df2.groupby(['City']).transform(np.size)
ValueError: Length mismatch: Expected axis has 5 elements, new values have 6 elements
</code></pre>
<p>Groupby不将nan分组:</p>
<pre><code>In [88]: [city for city, grp in df2.groupby(['City'])]
Out[88]: ['Baires', 'Caracas', 'Seattle']
</code></pre>
<p>要解决此问题,请使用<code>groupby/agg</code>:</p>
<pre><code>countcity = grouped.agg('count').rename(columns={'Name':'countcity'})
# countcity
# City
# Baires 2
# Caracas 2
# Seattle 1
</code></pre>
<p>然后将结果合并回<code>df2</code>:</p>
<pre><code>result = pd.merge(df2, countcity, left_on=['City'], right_index=True, how='outer')
print(result)
</code></pre>
<p>收益率</p>
<pre><code> City Name countcity
0 NaN Alice NaN
1 Seattle Bob 1
2 Baires Mallory 2
4 Baires Bob 2
3 Caracas Mallory 2
5 Caracas Mallory 2
</code></pre>
<hr/>
<p>问题4:您的意思是<em>什么是Pandas等价的SQL<code>select distinct</code>语句?</em></p>
<p>如果是这样的话,也许你正在寻找
<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unique.html" rel="nofollow">Series.unique</a>
或者可能迭代Groupby对象中的键,如中所述</p>
<pre><code>[city for city, grp in df2.groupby(['City'])]
</code></pre>