将访问查询转换为Python脚本

时间:2018-09-21 12:07:41

标签: python sql dataframe

我有一个要转换为Python脚本的访问查询:

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"));

我在数据框中存储了Functional_Details: df_functional_details

我无法理解如何继续执行python脚本。

到目前为止,我已经尝试过:

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 个答案:

答案 0 :(得分:0)

首先,选择适用条件的行(注意括号和&代替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')]

然后,执行分组逻辑:

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

您现在有了一个groupby对象,可以进一步对其进行操作和过滤:

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

您可能需要根据实际数据集的外观来调整组过滤。

进一步阅读: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.filter.html