我很惊讶你的第一种情况能成功。 但如果你给出一个简单版本的数据框架,可能会有帮助。
既然你没有这样做,我就只好编一个了:(In [321]: df = pd.DataFrame([[1,'foo'],[2,'bar']])
In [322]: df
Out[322]:
0 1
0 1 foo
1 2 bar
首先看一下 index: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='
In [325]: df.index.values.astype(str)+'_'
---------------------------------------------------------------------------
UFuncTypeError Traceback (most recent call last)
in
----> 1 df.index.values.astype(str)+'_'
UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype(' dtype('
+/add 没有为numpy字符串定义
现在看看字符串列。In [330]: df[1].values
Out[330]: array(['foo', 'bar'], dtype=object) # pandas uses python strings
将该数组转换为numpy str也会产生同样的错误:In [331]: df[1].values.astype(str)
Out[331]: array(['foo', 'bar'], dtype='
In [332]: df.index.values.astype(str)+df[1].values.astype(str)
---------------------------------------------------------------------------
UFuncTypeError Traceback (most recent call last)
in
----> 1 df.index.values.astype(str)+df[1].values.astype(str)
UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype(' dtype('
这就是为什么我想知道为什么你的第一个例子会出现错误.
如果我把对象dtype字符串保持原样。In [333]: df.index.values.astype(str)+df[1].values
Out[333]: array(['0foo', '1bar'], dtype=object)
numpy 转换为 index 数组到对象dtype(通用dtype),并进行逐元的 +对于 python 字符串来说,这就是连接。
将这一思想应用于带有'_'的情况。In [334]: df.index.values.astype(str).astype(object)+'_'+df[1].values
Out[334]: array(['0_foo', '1_bar'], dtype=object)