Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas convert mixed types to string

Given the following dataframe:

DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D','D','D'], 
'mixed': [2016.0, 2017.0, 'sweatervest', 20, 209, 21]})
DF

    COL1    mixed
0   A       2016.0
1   B       2017.0
2   C       sweatervest
3   D       20
4   D       209 
5   D       21

I want to convert 'mixed' to an object such that all numbers are integers as strings and all strings remain, of course, strings. The desired output is as follows:

    COL1    mixed
0   A       2016
1   B       2017
2   C       sweatervest
3   D       20
4   D       209 
5   D       21

Background info:

Originally, 'mixed' was part of a data frame taken from a CSV that mainly consisted of numbers, with some strings here and there. When I tried converting it to string, some numbers ended up with '.0' at the end.

like image 678
Dance Party Avatar asked Oct 23 '15 23:10

Dance Party


2 Answers

try:

DF['mixed']=DF.mixed.astype(object)

this results in:

DF['mixed']

0           2016
1           2017
2    sweatervest
3             20
4            209
5             21
Name: mixed, dtype: object
like image 170
JAB Avatar answered Oct 08 '22 22:10

JAB


df.mixed = df.mixed.apply(lambda elt: str(int(elt)) if isinstance(elt, float) else str(elt))

This calls the lambda elt: str(int(elt)) if isinstance(elt, float) else str(elt) function over each element of the 'mixed' column.

Note: This assumes that all of your floats are convertible to integers, as you implied in your comments on your question.

like image 41
gbrener Avatar answered Oct 08 '22 22:10

gbrener