steve at pearwood.info
Fri Dec 30 19:28:09 EST 2016
On Fri, Dec 30, 2016 at 04:46:26PM +0000, Albert-Jan Roskam wrote:
> Why does the call to str() below return '1' and not 'one'?
Because the literals 1, 2, 3 etc are hard-coded in the interpreter to
return objects of type `int`. Shadowing the name in the builtins module
doesn't change the type of object the literals return.
# Python 2.7
py> import __builtin__
py> class MyInt(int):
py> __builtin__.int = MyInt
Python 3 is the same, except you would import `builtins` instead of
`__builtin__`. (Do not use `__builtins__` with an "s".)
So I'm afraid that unfortunately, or perhaps fortunately, there's no way
to do what you are trying to do. You would have to modify the Python
> Should I implement __new__ because int is immutable?
That won't help.
> 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
Can you be a little more specific about what you are doing? Wouldn't you
be recoding the values of a datafile using an external editor?
How stupid is the code below on a scale from 1-10? Remember
> I only intend to use it while debugging the given script.
> 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]
I don't understand what I'm reading there, or what you're attempting to
More information about the Tutor