我将Pandas'ver 0.12.0'与Python 2.7结合使用,并具有如下数据框:
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
为String?
2)我最终将id
用于为数据帧建立索引。与具有整数索引相比,在数据帧中具有String索引会降低速度吗?
您可以将id的所有元素转换为str
使用apply
df.id.apply(str)
0 123
1 512
2 zhub1
3 12354.3
4 129
5 753
6 295
7 610
由OP编辑:
我认为这个问题与Python版本(2.7。)有关,这可行:
df['id'].astype(basestring)
0 123
1 512
2 zhub1
3 12354.3
4 129
5 753
6 295
7 610
Name: id, dtype: object
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句