zachi
zachi

Reputation: 537

I would like to convert an int to string in dataframe

I would like to convert a column in dataframe to a string it looks like this :

company department  id  family  name    start_date  end_date
abc sales   38221925    Levy    nali    16/05/2017  01/01/2018

I want to convert the id from int to string

I tried

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

and

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

got dtype('O')

I expect to receive string

Upvotes: 1

Views: 1434

Answers (3)

Ujjwal Gupta
Ujjwal Gupta

Reputation: 158

You can do that by using apply() function in this way:

data['id'] = data['id'].apply(lambda x: str(x))

This will convert all the values of id column to string.

You can ensure the type of the values like this:
type(data['id'][0]) (It is checking the first value of 'id' column)
This will give the output str.

And data['id'].dtype will give dtype('O') that is object.

You can also use data.info() to check all the information about that DataFrame.

Upvotes: 1

Paritosh Singh
Paritosh Singh

Reputation: 6246

This is intended behaviour. This is how pandas stores strings.

From the docs

Pandas uses the object dtype for storing strings.

For a simple test, you can make a dummy dataframe and check it's dtype too.

import pandas as pd
df = pd.DataFrame(["abc", "ab"])
df[0].dtype
#Output:
dtype('O')

Upvotes: 1

Tashun Sandaru
Tashun Sandaru

Reputation: 115

str(12)

>>'12'

Can easily convert to a String

Upvotes: 0

Related Questions