Pandas:将Series的数据类型更改为字符串

169

我使用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系列包含一些整数和字符串。它的默认 dtypeobject。我想将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来对数据框进行索引。与使用整数索引相比,使用字符串索引在数据框中是否会减慢速度?


1
不确定为什么您会得到astype输出的那个结果,因为它在我这里运行良好,至少在版本0.13.1中是如此,也许0.12.0有一个错误?针对您的第二个问题,是的,由于字符串比较不会比整数比较更快,因此可能会慢一些,但我建议您首先进行性能分析,同时这也取决于数据量大小。 - EdChum
你已经设置好了列,对吧?df['id'] = df['id'].astype(str) - Andy Hayden
@Andy Hayden,是的,我做了这个约定,但我认为输出结果是意外的。 - Zhubarb
以何种方式出现了意外情况? - Andy Hayden
1
它只返回每个Series元素的第一个字符,就像我在问题中使用df['id'].astype(str)一样。 - Zhubarb
显示剩余2条评论
11个回答

-2

对我来说,.to_string() 运行正常

df['id']=df['id'].to_string()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接