[Tutor] ReadableInt
Albert-Jan Roskam
sjeik_appie at hotmail.com
Fri Dec 30 11:46:26 EST 2016
Hi,
Why does the call to str() below return '1' and not 'one'? Should I implement __new__ because int is immutable? I have a datafile that contains values and an associated metadata file with the associated labels. I need to recode the values. Because just using the values is a bit error prone I would like to see the associated labels while debugging. How stupid is the code below on a scale from 1-10? Remember I only intend to use it while debugging the given script.
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class ReadableInt(int):
... def __str__(self):
... return {1: "one", 2: "two"}.get(self, self)
...
>>> builtins.int = ReadableInt
>>> str(1) # I expected 'one'
'1'
>>> builtins.int.__str__
<function ReadableInt.__str__ at 0x00ADFB70>
Btw, initially I hoped to be able to do this with the (newish) pandas dtype 'category', but unless
I am overlooking something, but this does not seem possible:
>>> import pandas as pd
>>> pd.Categorical.from_codes([1, 2], ["one", "two"], ordered=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Albert-Jan\AppData\Local\Programs\Python\Python35-32\lib\site-p
ackages\pandas\core\categorical.py", line 471, in from_codes
raise ValueError("codes need to be between -1 and "
ValueError: codes need to be between -1 and len(categories)-1
>>> pd.Categorical.from_codes([0, 1], ["one", "two"], ordered=True)
[one, two]
Categories (2, object): [one < two]
Happy coding in 2017!
Best wishes,
Albert-Jan
More information about the Tutor
mailing list