Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: change data type of Series to String

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?

like image 244
Zhubarb Avatar asked Mar 06 '14 17:03

Zhubarb


People also ask

How do you convert a series to a string?

As we can see in the output, the Series. to_string() function has successfully rendered a string representation to the given object. Example #2: Use Series. to_string() function to render a string representation of the given series object.

How do I change the datatype of a series in pandas?

Change data type of a series in PandasUse a numpy. dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, …}, where col is a column label and dtype is a numpy. dtype or Python type to cast one or more of the DataFrame's columns to column-specific types.

How do you change a datatype to a string in Python?

There are two ways for changing any data type into a String in Python : Using the str() function. Using the __str__() function.

How do I change a column type to a string?

If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df.


1 Answers

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 
like image 106
Amit Verma Avatar answered Sep 18 '22 04:09

Amit Verma