我在 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
来索引数据帧。与具有整数索引相比,数据帧中的字符串索引会减慢速度吗?
原文由 Zhubarb 发布,翻译遵循 CC BY-SA 4.0 许可协议
反映最新实践的新答案:截至目前(v1.2.4),
astype('str')
和astype(str)
都不起作用。根据文档,可以通过以下方式将 Series 转换为字符串数据类型: