Python – Pandas mixes value columns to strings

Pandas mixes value columns to strings… here is a solution to the problem.

Pandas mixes value columns to strings

I have a column in the Pandas data frame with mixed values, i.e. string, float, and number. I want to convert all values in this column to strings, but it doesn’t allow me to do so :

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

UnicodeEncodeError: 'ascii' codec can't encode character u'\u201d' in position 1: ordinal not in range(128)

I know that normally you can use

 str(0.05) --> '0.05'

But now, when I convert the column to a string, it still leaves float as float.

Solution

Since the column is unicode, you can try encoding it:

df['text'] = df['text'].apply(lambda x: x.encode('utf-8').strip())

Related Problems and Solutions