<p>我很惊讶你的第一个案子成功了。但如果您提供一个简单版本的数据框架,可能会有所帮助</p>
<p>既然你没有那样做,我就得编一个:(</p>
<pre><code>In [321]: df = pd.DataFrame([[1,'foo'],[2,'bar']])
In [322]: df
Out[322]:
0 1
0 1 foo
1 2 bar
</code></pre>
<p>首先看一下<code>index</code>:</p>
<pre><code>In [323]: df.index.values
Out[323]: array([0, 1]) # numeric in my case
In [324]: df.index.values.astype(str)
Out[324]: array(['0', '1'], dtype='<U21') # numpy dtype
In [325]: df.index.values.astype(str)+'_'
-
UFuncTypeError Traceback (most recent call last)
<ipython-input-325-230387b2895a> in <module>
> 1 df.index.values.astype(str)+'_'
UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')
</code></pre>
<p>未为numpy字符串定义<code>+/add</code></p>
<p>现在查看字符串列:</p>
<pre><code>In [330]: df[1].values
Out[330]: array(['foo', 'bar'], dtype=object) # pandas uses python strings
</code></pre>
<p>将该数组转换为numpy str会产生相同的错误:</p>
<pre><code>In [331]: df[1].values.astype(str)
Out[331]: array(['foo', 'bar'], dtype='<U3')
In [332]: df.index.values.astype(str)+df[1].values.astype(str)
-
UFuncTypeError Traceback (most recent call last)
<ipython-input-332-7bc2436a1bf8> in <module>
> 1 df.index.values.astype(str)+df[1].values.astype(str)
UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')
</code></pre>
<p>这就是为什么我想知道为什么你的第一个案子会成功</p>
<p>如果我将对象数据类型字符串保持原样:</p>
<pre><code>In [333]: df.index.values.astype(str)+df[1].values
Out[333]: array(['0foo', '1bar'], dtype=object)
</code></pre>
<p><code>numpy</code>将<code>index</code>数组转换为对象数据类型(公共数据类型),并逐元素执行<code>+</code>,对于python字符串来说,这是串联</p>
<p>把这个想法用一个“u”来表示:</p>
<pre><code>In [334]: df.index.values.astype(str).astype(object)+'_'+df[1].values
Out[334]: array(['0_foo', '1_bar'], dtype=object)
</code></pre>