<p>使用示例数据帧</p>
<pre><code>In [138]: df
Out[138]:
col1 col2 col3 newcol
0 a 1 x Wow
1 b 2 y Dud
2 c 1 z Wow
In [139]: df['newcol']
Out[139]:
0 Wow
1 Dud
2 Wow
Name: newcol, dtype: object
In [140]: type(_)
Out[140]: pandas.core.series.Series
</code></pre>
<p>选择一列给我一个系列;不需要另一个系列包装器</p>
<pre><code>In [141]: pd.Series(df['newcol'])
Out[141]:
0 Wow
1 Dud
2 Wow
Name: newcol, dtype: object
</code></pre>
<p>我们可以把它列在一个列表中,但这没有任何好处:</p>
<pre><code>In [142]: [pd.Series(df['newcol'])]
Out[142]:
[0 Wow
1 Dud
2 Wow
Name: newcol, dtype: object]
In [143]: len(_)
Out[143]: 1
</code></pre>
<p>我们可以将值提取为numpy数组:</p>
<pre><code>In [144]: pd.Series(df['newcol']).values
Out[144]: array(['Wow', 'Dud', 'Wow'], dtype=object)
</code></pre>
<p>我们可以对数组或序列中的每个元素应用字符串切片-使用列表理解:</p>
<pre><code>In [145]: [astr[:2] for astr in _144]
Out[145]: ['Wo', 'Du', 'Wo']
In [146]: [astr[:2] for astr in _141]
Out[146]: ['Wo', 'Du', 'Wo']
</code></pre>
<p>列表理解不一定是最“高级”的方式,但它是一个良好的开端。实际上它接近最佳,因为切片字符串必须使用字符串方法;没有其他人实现字符串切片</p>
<p><code>pandas</code>有一个<code>str</code>方法用于将字符串方法应用于序列:</p>
<pre><code>In [147]: ds = df['newcol']
In [151]: ds.str.slice(0,2) # or ds.str[:2]
Out[151]:
0 Wo
1 Du
2 Wo
Name: newcol, dtype: object
</code></pre>
<p>这比列表理解更清晰、更美观,但实际上速度较慢</p>