Convert column in pandas dataframe from int to string

I have a dataframe in pandas with mixed int and str data columns. I want to combine the columns in the data frame first. To do this, I need to convert the int column to str . I tried to do the following:

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

or

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

but in both cases this does not work, and I get the error message "it is not possible to combine str and int objects". Joining two str columns works fine.

+75
python string pandas int dataframe
Jul 30 '13 at 14:53
source share
4 answers
 In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB')) In [17]: df Out[17]: AB 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 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' 

Remember to assign the result back:

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



Convert whole frame

 In [21]: df.applymap(str) Out[21]: AB 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) 
+86
Jul 30 '13 at 14:59
source share

Change the data type of the DataFrame column:

In int:

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

To str:

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

+69
Feb 06 '16 at 12:24
source share

Warning Both solutions given ( astype () and apply () ) do not store NULL values ​​in either the nano or the None form.

 import pandas as pd import numpy as np df = pd.DataFrame([None,'string',np.nan,42], index=[0,1,2,3], columns=['A']) df1 = df['A'].astype(str) df2 = df['A'].apply(str) print df.isnull() print df1.isnull() print df2.isnull() 

I believe this is fixed with to_string ()

+11
May 16 '17 at 17:49
source share

Use this:

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

0
Jun 04 '19 at 1:16
source share



All Articles