On 01/08/2014 15:26, Alex van der Spek wrote:
On Fri, 01 Aug 2014 12:45:12 +0000, Alex van der Spek wrote:
With a dict like so:
cond = {'a': 1, 'b': 1, 'c': 1,
'A': 0, 'B', 0, 'C':0}
how would you make a boolean expression like this:
bool = (('a' == 1) & ('A' == 0) |
('b' == 1) & ('B' == 0) |
('c' == 1) & ('C' == 0))
The fact that lowercase and uppercase keys are stringed together with &
is intentional albeit the actual condition is a bit more tricky.
I've tried several approaches using eval() on a string built from the
dict but landed with just spelling it out literally.
Any pointers welcome.
Alex
I am sorry, the problem is ill posed.
'a', 'A' and so forth are my failed attempt to shorthand.
In reality the dict's keys are column names in a pandas dataframe df.
The boolean expression would therefore look like:
bool = ((df['a'] == 1) & (df['A'] == 0) |
(df['b'] == 1) & (df['B'] == 0) |
(df['c'] == 1) & (df['C'] == 0))
See this
http://stackoverflow.com/questions/19482970/python-get-list-from-pandas-dataframe-column-headers
to get the column names. Combine this with Steven D'Aprano's earlier
answer using any() and I suspect you're there.
I do know eval() lends itself to code injection but can't say I am
fully aware of its dangers. It seemed like a handy tool to me.
It strikes me as being like looking down the gun barrel to see if
there's a bullet loaded whilst holding the trigger. Best avoided but
there's always the "consenting adults" approach here :)
This newsgroup scares me, it appears to be for professional computer
scientists only, the theoretical part is sometimes too much for this
practical physicist with an old background in FORTRAN.
If you're smart enough to state that your first question was ill posed,
you're smart enough to ask questions when you don't understand.
Is there a better place to ask questions of this nature?
No :)
Alex van der Spek
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
--
https://mail.python.org/mailman/listinfo/python-list