Change dtype of my colums

User 2504 | 10/28/2015, 4:21:58 PM

Hi, I'm a beginner and I'm doing data manipulation. I have a question : I have 47 colums, and during the import of my csv, some of my colums are in str while they should be int. Could you tell me how I could change that ? Tks a lot

Comments

User 1592 | 10/28/2015, 4:24:59 PM

This is very easy: data['mycolumn'] = data['mycolumn'].astype(int)

An alternative solution is to use the columntypehints field that will tell GraphLab Create to read this column as int, see the documentation here: https://dato.com/products/create/docs/generated/graphlab.SFrame.read_csv.html.


User 2504 | 10/28/2015, 9:00:59 PM

Tks a lot Danny - indeed basic, I'm learning :-)

When I run it I get the message below, do you see why ? here what I run : makeup['CTR'] = makeup['CTR'].astype(int) and what I got : ` RuntimeError Traceback (most recent call last) <ipython-input-20-7649b63bd1ce> in <module>() ----> 1 makeup['CTR'] = makeup['CTR'].astype(int)

/Users/Arnaud/.graphlab/anaconda/lib/python2.7/site-packages/graphlab/datastructures/sarray.pyc in astype(self, dtype, undefinedonfailure) 2206 2207 with cythoncontext(): -> 2208 return SArray(proxy=self.proxy.astype(dtype, undefinedon_failure)) 2209 2210 def clip(self, lower=float('nan'), upper=float('nan')):

/Users/Arnaud/.graphlab/anaconda/lib/python2.7/site-packages/graphlab/cython/context.pyc in exit(self, exctype, excvalue, traceback) 47 if not self.showcythontrace: 48 # To hide cython trace, we re-raise from here ---> 49 raise exctype(excvalue) 50 else: 51 # To show the full trace, we do nothing and let exception propagate

RuntimeError: Runtime Exception. Unable to interpret as the target type. `


User 4 | 10/28/2015, 9:20:17 PM

Hi @ArnaudPlas, it seems you have some values in this column that are not valid int values. Namely, empty string ('').

You could replace all the empty string with None values (which are allowed in an int column) by running: makeup['CTR'] = makeup['CTR'].apply(lambda x: None if x == '' else x)

Then, try the astype conversion again, once the empty string values have been removed.


User 2504 | 10/28/2015, 9:27:27 PM

OH yes that WORKS ! Thanks so much @Zach