Conversion of Access Query to Python Script

Viewed 93

I have an Access Query which I want to convert into Python Script:

SELECT 
 [Functional_Details].Customer_No, 
 Sum([Functional_Details].[SUM(Incoming_Hours)]) AS [SumOfSUM(Incoming_Hours)], 
 Sum([Functional_Details].[SUM(Incoming_Minutes)]) AS [SumOfSUM(Incoming_Minutes)], 
 Sum([Functional_Details].[SUM(Incoming_Seconds)]) AS [SumOfSUM(Incoming_Seconds)], 
 [Functional_Details].Rate, 
 [Functional_Details].Customer_Type
FROM [Functional_Details]
WHERE(
    (([Functional_Details].User_ID) Not In ("IND")) 
    AND 
    (([Functional_Details].Incoming_ID)="Airtel") 
    AND 
    (([Functional_Details].Incoming_Category)="Foreign") 
    AND 
    (([Functional_Details].Outgoing_ID)="Airtel") 
    AND 
    (([Functional_Details].Outgoing_Category)="Foreign") 
    AND 
    (([Functional_Details].Current_Operation)="NO") 
    AND 
    (([Functional_Details].Active)="NO")
)
GROUP BY [Functional_Details].Customer_No, [Functional_Details].Rate, [Functional_Details].Customer_Type
HAVING ((([Functional_Details].Customer_Type)="Check"));

I have Functional_Details stored in a dataframe: df_functional_details

I am not able to understand how to proceed with the python script.

So far I have tried:

df_fd_temp=df_functional_details.copy()

if(df_fd_temp['User_ID'] != 'IND' 
    and df_fd_temp['Incoming_ID'] == 'Airtel' 
    and df_fd_temp['Incoming_Category'] == 'Foreign' 
    and df_fd_temp['Outgoing_ID'] == 'Airtel'
    and df_fd_temp['Outgoing_Category'] == 'Foreign' 
    and df_fd_temp['Current_Operation'] == 'NO' 
    and df_fd_temp['Active'] == 'NO'):
     df_fd_temp.groupby(['Customer_No','Rate','Customer_Type']).groups
     df_fd_temp[df_fd_temp['Customer_Type'].str.contains("Check")]
1 Answers

First, select the rows where the conditions apply (note the parentheses and & instead of and):

df_fd_temp = df_fd_temp[(df_fd_temp['User_ID'] != 'IND') &
    (df_fd_temp['Incoming_ID'] == 'Airtel') &
    (df_fd_temp['Incoming_Category'] == 'Foreign') & 
    (df_fd_temp['Outgoing_ID'] == 'Airtel') &
    (df_fd_temp['Outgoing_Category'] == 'Foreign') & 
    (df_fd_temp['Current_Operation'] == 'NO') &
    (df_fd_temp['Active'] == 'NO')]

Then, do the group-by logic:

 df_grouped = df_fd_temp.groupby(['Customer_No','Rate','Customer_Type'])

You now have a groupby object, which you can further manipulate and filter:

df_grouped.filter(lambda x: "Check" in x['Customer_Type'])

You might need to tweak the group filtering based on what your actual dataset looks like.

Further reading: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.filter.html

Related