熊猫:将系列的数据类型更改为字符串

新手上路,请多包涵

我在 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 许可协议

阅读 365
2 个回答

反映最新实践的新答案:截至目前(v1.2.4), astype('str')astype(str) 都不起作用。

根据文档,可以通过以下方式将 Series 转换为字符串数据类型:

 df['id'] = df['id'].astype("string")

df['id'] = pandas.Series(df['id'], dtype="string")

df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)

原文由 rocksNwaves 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 --- 将 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

原文由 Amit 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题