我使用Python 2.7中的Pandas 'ver 0.12.0',并且有一个如下的数据框:
df = pd.DataFrame({'id' : [123,512,'zhub1', 12354.3, 129, 753, 295, 610],
'colour': ['black', 'white','white','white',
'black', 'black', 'white', 'white'],
'shape': ['round', 'triangular', 'triangular','triangular','square',
'triangular','round','triangular']
}, columns= ['id','colour', 'shape'])
id
系列包含一些整数和字符串。它的默认 dtype
是 object
。我想将id
的所有内容都转换为字符串。我尝试了astype(str)
,它生成了下面的输出。
df['id'].astype(str)
0 1
1 5
2 z
3 1
4 1
5 7
6 2
7 6
1) 如何将所有的id
元素转换为字符串?
2) 我最终会使用id
来对数据框进行索引。与使用整数索引相比,使用字符串索引在数据框中是否会减慢速度?
astype
输出的那个结果,因为它在我这里运行良好,至少在版本0.13.1中是如此,也许0.12.0有一个错误?针对您的第二个问题,是的,由于字符串比较不会比整数比较更快,因此可能会慢一些,但我建议您首先进行性能分析,同时这也取决于数据量大小。 - EdChumdf['id'].astype(str)
一样。 - Zhubarb