Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a column within pandas dataframe from int to string

I have a dataframe in pandas with mixed int and str data columns. I want to concatenate first the columns within the dataframe. To do that I have to convert an int column to str. I've tried to do as follows:

mtrx['X.3'] = mtrx.to_string(columns = ['X.3']) 

or

mtrx['X.3'] = mtrx['X.3'].astype(str) 

but in both cases it's not working and I'm getting an error saying "cannot concatenate 'str' and 'int' objects". Concatenating two str columns is working perfectly fine.

like image 346
Malfet Avatar asked Jul 30 '13 14:07

Malfet


People also ask

How do I convert a column into a DataFrame to a string?

You can convert the column “Fee” to a string by simply using DataFrame. apply(str) , for example df["Fee"]=df["Fee"]. apply(str) .

How do you change an int to a string in Python?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .

How do I convert a string to a column int?

Use pandas DataFrame. astype(int) and DataFrame. apply() methods to convert a column to int (float/string to integer/int64/int32 dtype) data type. If you are converting float, I believe you would know float is bigger than int type, and converting into int would lose any value after the decimal.


2 Answers

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))  In [17]: df Out[17]:     A  B 0  0  1 1  2  3 2  4  5 3  6  7 4  8  9  In [18]: df.dtypes Out[18]:  A    int64 B    int64 dtype: object 

Convert a series

In [19]: df['A'].apply(str) Out[19]:  0    0 1    2 2    4 3    6 4    8 Name: A, dtype: object  In [20]: df['A'].apply(str)[0] Out[20]: '0' 

Don't forget to assign the result back:

df['A'] = df['A'].apply(str) 

Convert the whole frame

In [21]: df.applymap(str) Out[21]:     A  B 0  0  1 1  2  3 2  4  5 3  6  7 4  8  9  In [22]: df.applymap(str).iloc[0,0] Out[22]: '0' 

df = df.applymap(str) 
like image 130
Jeff Avatar answered Sep 22 '22 06:09

Jeff


Change data type of DataFrame column:

To int:

df.column_name = df.column_name.astype(np.int64)

To str:

df.column_name = df.column_name.astype(str)

like image 36
tanaque Avatar answered Sep 23 '22 06:09

tanaque