Pandas: change data type of Series to String

穿精又带淫゛_ 提交于 2019-11-26 08:59:56

问题


I use Pandas \'ver 0.12.0\' with Python 2.7 and have a dataframe as below:

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\'])

The id Series consists of some integers and strings. Its dtype by default is object. I want to convert all contents of id to strings. I tried astype(str), which produces the output below.

df[\'id\'].astype(str)
0    1
1    5
2    z
3    1
4    1
5    7
6    2
7    6

1) How can I convert all elements of id to String?

2) I will eventually use id for indexing for dataframes. Would having String indices in a dataframe slow things down, compared to having an integer index?


回答1:


You can convert all elements of id to str using apply

df.id.apply(str)

0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610

Edit by OP:

I think the issue was related to the Python version (2.7.), this worked:

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



回答2:


You must assign it, like this:-

df['id']= df['id'].astype(str)



回答3:


Personally none of the above worked for me. What did:

new_str = [str(x) for x in old_obj][0]



回答4:


Man I am so frustrated with python! None of these solutions worked for me!! I`m using python 3 at Google Colaborative. I also tryed another solution

df[['id']] = df[['id']].astype(str)

But it has also not worked



来源:https://stackoverflow.com/questions/22231592/pandas-change-data-type-of-series-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!