I have three activities (A, B, C) that need to return a string = 'True' in order for the If block to run its True activities, otherwise False activities.
Scenario 1 (All True):
A = True
B = True -> if A & B & C = True then True
C = True
Scenario 2 (At least one False):
True
False -> if A & B & C != True then False
True
I have tried to simplify the expression to this;
#and(
equals('True',
'True'), # True = True, True
and(
equals('True',
'True'), # True = True, True
equals('True',
'True') # True = True, True
) # True & True, True
# True & True, return True
)
However, this throws an error:
The function 'bool' was invoked with a parameter that is not valid. The value cannot be converted to the target type
How can I go about evaluating all three (3) conditions?
I have also tried using another and() such that it becomes this to no avail (same error msg):
#and(
and(
equals('True',
'True'),
true
),
and(
equals('True',
'True'),
equals('True',
'True')
)
)
True Condition
#and(equals(Activity A),'True'),equals(Activity B),'True'))-Set a variable Z =true
#and(equals(Activity Z),'True'),equals(Activity C),'True'))-Set a variable result =true
False Condition
#or(equals(Activity A),'False'),equals(Activity B),'False'))-Set a variable Z =False
#or(equals(Activity Z),'False'),equals(Activity C),'False'))-Set a variable result =False
This seems to be one way of solving it.
#and(
bool(equals('True',
'True')),
and(
equals('True',
'True'),
equals('True',
'True')
)
)
Related
I would need to write a SQL question based on conditions:
in Condition 1:
SELECT
*
FROM
table_1
WHERE
col_1 IS NULL
AND col_2 IS NOT NULL
and in Condition 2:
SELECT
*
FROM
table_1
WHERE
col_1 IS NULL
How would I be able to achieve this easily in Python? I know I can do filters later on but that's not super efficient as it should be.
The solution used in many tools: Make initial query with dummy TRUE WHERE clause, then depending on conditions can be concatenated with additional filters like this (simplified code):
query = 'select * from table where 1 = 1' # WHERE with dummy TRUE condition
# it can be WHERE TRUE
condition1 = True; # if both conditions are False, query will be without filters
condition2 = True;
filter1='Col1 is not null'
filter2='Col2 is not null'
if condition1:
query = query+' and '+ filter1
if condition2:
query = query+' and '+ filter2
print(query)
Result:
select * from table where 1 = 1 and Col1 is not null and Col2 is not null
More elegant solution using pypika - python query builder. You can build the whole query including table, fields, where filters and joins:
from pypika import Query, Table, Field
table = Table('table')
q = Query.from_(table).select(Field('col1'), Field('col2'))
condition1 = True;
condition2 = True;
if condition1:
q = q.where(
table.col1.notnull()
)
if condition2:
q = q.where(
table.col2.notnull()
)
print(q)
Result:
SELECT "col1","col2" FROM "table" WHERE NOT "col1" IS NULL AND NOT "col2" IS NULL
I'm trying to iterate over a list I have with a column in a dataframe which has list in each row.
list1 = ['installing','install','installed','replaced','repair','repaired','replace','part','used','new']
df[lwr_nopunc_spc_nostpwrd].head(3)
['daily', 'ask', 'questions']
['daily', 'system', 'check', 'task', 'replace']
['inspection', 'complete', 'replaced', 'horizontal', 'sealing', 'blade', 'inspection', 'complete', 'issues', 'found']
Now, I want to get two new columns in my dataframe that should show true or false if <new column one> any one of the item in df[lwr_nopunc_spc_nostpwrd] row is present in list1 <new columns two> if all the items in list1 one are present in df[lwr_nopunc_spc_nostpwrd] row
Please let me know how than can be achieved.I tried all() and any() methods but that doesn't seem to work.
def prt_usd(row):
return(any(item in query['lwr_nopunc_spc_nostpwrd'] for item in part))
for row in query['lwr_nopunc_spc_nostpwrd']:
prt_usd(query['lwr_nopunc_spc_nostpwrd'])
you can do it apply and set like:
# I changed the list to the second row to show that the column all works
list1 = ['daily', 'system', 'check', 'task', 'replace']
# create a set from it
s1 = set(list1)
# for any word, check that the intersection of s1
# and the set of the list in this row is not empty
df['col_any'] = df['lwr_nopunc_spc_nostpwrd'].apply(lambda x: any(set(x)&s1))
# for all, subtract the set of this row from the set s1,
# if not empty then it return True with any
# that you reverse using ~ in front of it to get True if all words from s1 are in this row
df['col_all'] = ~df['lwr_nopunc_spc_nostpwrd'].apply(lambda x: any(s1-set(x)))
print (df)
lwr_nopunc_spc_nostpwrd col_any col_all
0 [daily, ask, questions] True False
1 [daily, system, check, task, replace] True True
2 [inspection, complete, replaced, horizontal, s... False False
You could use some set arithmetic with list comprehensions, like this (note that I simplified your examples to have more obvious test cases):
import pandas as pd
list1 = ['installing', 'replace']
set1 = set(list1)
df = pd.DataFrame({'col1': [['daily', 'ask'],
['daily', 'replace'],
['installing', 'replace', 'blade']]})
# new1 should be True when the intersection of list1 with the row from col1 is not empty
df['new1'] = [set1.intersection(set(row)) != set() for row in df.col1]
# new2 should be True when list1 is a subset of the row from col1
df['new2'] = [set1.issubset(set(row)) for row in df.col1]
df
col1 new1 new2
0 [daily, ask] False False
1 [daily, replace] True False
2 [installing, replace, blade] True True
Error given when adding query that runs in SQL developer but not in MS Query. Seems to not like my nested query.
Code I am using:
SELECT ORDER_DATE
,SALES_ORDER_NO
,CUSTOMER_PO_NUMBER
,DELIVER_TO
,STATUS
,ITEM_NUMBER
,DESCRIPTION
,ORD_QTY
,SUM(QUANTITY) AS ON_HAND
,PACKAGE_ID
,PACKAGE_STATUS
,MAX(TRAN_DATE) AS LAST_TRANSACTION
,MIN(DAYS) AS DAYS
FROM (
SELECT TRUNC(SH.ORDER_DATE) AS ORDER_DATE
,SH.SALES_ORDER_NO
,SH.CUSTOMER_PO_NUMBER
,SH.SHIP_CODE AS DELIVER_TO
,SH.STATUS
,SB.ITEM_NUMBER
,IM.DESCRIPTION
,SB.ORD_QTY
,BID.QUANTITY
,SPM.PACKAGE_ID
,CASE
WHEN SPM.SHIPPED = 'Y'
THEN 'SHIPPED'
WHEN SPM.STATUS = 'C'
THEN 'PACKED'
WHEN BID.QUANTITY IS NOT NULL
THEN 'AVAILABLE'
WHEN BID.QUANTITY IS NULL
THEN 'UNAVAILABLE'
END AS PACKAGE_STATUS
,CASE
WHEN SPM.SHIPPED = 'Y'
THEN TRUNC(SPM.BILLING_DATE)
WHEN SPM.STATUS = 'C'
THEN TRUNC(SPM.END_TIME)
WHEN BID.QUANTITY IS NOT NULL
THEN TRUNC(BID.ACTIVATION_TIME)
END AS TRAN_DATE
,CASE
WHEN SPM.SHIPPED = 'Y'
THEN ROUND(SYSDATE - SPM.BILLING_DATE, 0)
WHEN SPM.STATUS = 'C'
THEN ROUND(SYSDATE - SPM.END_TIME, 0)
WHEN BID.QUANTITY IS NOT NULL
THEN ROUND(SYSDATE - BID.ACTIVATION_TIME, 0)
END AS DAYS
FROM SO_HEADER SH
LEFT JOIN SO_BODY SB ON SB.SO_HEADER_TAG = SH.SO_HEADER_TAG
LEFT JOIN SO_PACKAGE_MASTER SPM ON SPM.PACKAGE_ID = SB.PACKAGE_ID
LEFT JOIN ITEM_MASTER IM ON IM.ITEM_NUMBER = SB.ITEM_NUMBER
LEFT JOIN V_BIN_ITEM_DETAIL BID ON BID.ITEM_NUMBER = SB.ITEM_NUMBER
WHERE SH.ORDER_TYPE = 'MSR'
AND (
SB.REASON_CODE IS NULL
OR SB.REASON_CODE NOT LIKE 'CANCEL%'
)
AND (
IM.DESCRIPTION NOT LIKE '%CKV%'
OR IM.DESCRIPTION IS NULL
AND IM.ITEM_NUMBER IS NOT NULL
)
)
WHERE PACKAGE_STATUS <> 'SHIPPED'
GROUP BY ORDER_DATE
,SALES_ORDER_NO
,CUSTOMER_PO_NUMBER
,DELIVER_TO
,STATUS
,ITEM_NUMBER
,DESCRIPTION
,ORD_QTY
,PACKAGE_ID
,PACKAGE_STATUS
ORDER BY (
CASE PACKAGE_STATUS
WHEN 'AVAILABLE'
THEN 1
WHEN 'UNAVAILABLE'
THEN 2
WHEN 'PACKED'
THEN 3
END
)
,LAST_TRANSACTION;
Is there any option I can select that will allow me to run this query?
The is a dataframe(df1) like the following:
eye_l eye_r nose mouse ear eyebrow_l eyebrow_r ...
34_35_a -1_-1_-1 45_66_b 45_64_a 78_87_a -1_-1_-1 -1_-1_-1
35_38_a -1_-1_-1 75_76_b -1_-1_-1 38_79_a -1_-1_-1 -1_-1_-1
64_43_a -1_-1_-1 85_66_b 65_45_a 87_45_a -1_-1_-1 -1_-1_-1
....................................................................
I want to just delete the columns that all the value of a column is -1_-1_-1 (such as eye_r, eyebrow_1, eyebrow_r), and please notice that some columns may have a number (not all) of value is -1_-1_-1 will be kept.
I know that there is code like:
df1. drop(['eye_r', 'eyebrow_l', 'eyebrow_r '], axis=1, inplace=True)
But all the value is -1_-1_-1 of columns is not just three, there may be 100, and also there is a number of dataframes like such kind of dataframe. I want to process this issue in common method.
Thanks
Use boolean indexing with DataFrame.all and change condition to != or
DataFrame.any with inverting mask by ~:
df = df.loc[:, (df != '-1_-1_-1').any()]
Or:
df = df.loc[:, ~(df == '-1_-1_-1').all()]
print (df)
eye_l nose mouse ear
0 34_35_a 45_66_b 45_64_a 78_87_a
1 35_38_a 75_76_b -1_-1_-1 38_79_a
2 64_43_a 85_66_b 65_45_a 87_45_a
Detail:
print (df != '-1_-1_-1')
eye_l eye_r nose mouse ear eyebrow_l eyebrow_r
0 True False True True True False False
1 True False True False True False False
2 True False True True True False False
print ((df != '-1_-1_-1').any())
eye_l True
eye_r False
nose True
mouse True
ear True
eyebrow_l False
eyebrow_r False
dtype: bool
I'm trying to check whether a variable exists in an SQLite3 db. Unfortunately I can not seem to get it to work. The airports table contains 3 colums, with ICAO as the first column.
if c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')") is True:
print("Found!")
else:
print("Not found...")
The code runs without any errors, but the result is always the same (not found).
What is wrong with this code?
Try this instead:
c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')")
if c.fetchone():
print("Found!")
else:
print("Not found...")
Return value of cursor.execute is cursor (or to be more precise reference to itself) and is independent of query results. You can easily check that:
>>> r = c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')")
>>> r is True
False
>>> r is False
False
>>> r is None
False
>>> r is c
True
From the other hand if you call cursor.fetchone result tuple or None if there is no row that passes query conditions. So in your case if c.fetchone(): would mean one of the below:
if (1, ):
...
or
if None:
...
Let's prepare a database to test it.
import sqlite3
c = sqlite3.connect(":memory:")
c.execute("CREATE TABLE airports (ICAO STRING, col2 STRING, col3 STRING)")
c.execute("INSERT INTO airports (ICAO, col2, col3) VALUES (?, ?, ?)", ('EHAM', 'value2', 'value3'))
Since your SELECT 1 FROM airports WHERE ICAO = 'EHAM' already serves the purpose of checking existence, let's use it directly, without the redundant SELECT EXISTS()
if c.execute("SELECT 1 FROM airports WHERE ICAO = 'EHAM'").fetchone():
print("Found!")
else:
print("Not found...")
the result is
Found!
Let's check a non-existent case
if c.execute("SELECT 1 FROM airports WHERE ICAO = 'NO-SUCH'").fetchone():
print("Found!")
else:
print("Not found...")
the result is
Not found...
If you just want to fix your code, you can try
if c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO = 'EHAM')").fetchone() == (1,):
print("Found!")
else:
print("Not found...")
the result is
Found!
Thanks for the answer from zero323, although the code snippet is wrong, as fetchone() does not return True or False. It only returns 1 for True and 0 for False. (binary) The following code works without problems in Python3:
response = self.connection.execute("SELECT EXISTS(SELECT 1 FROM invoices WHERE id=?)", (self.id, ))
fetched = response.fetchone()[0]
if fetched == 1:
print("Exist")
else:
print("Does not exist")
I don't have the reputation to comment. However, the comments and answers claiming that the top answer is incorrect are erroneous. In Python, 1 and 0 are synonymous with True and False, respectively. In fact, the substitution of 1 for True and 0 for False are very Pythonic, i.e. highly condoned in Python.
In short, the top answer of if c.fetchone(): is correct.
Checking for equality with 1, if c.fetchone() == 1:, is unnecessary and against Python best practices.