python - 将 Access 查询转换为 Python 脚本

标签 python sql dataframe

我有一个 Access 查询,我想将其转换为 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_function_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")]

最佳答案

首先,选择条件适用的行(注意括号和 & 而不是 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

关于python - 将 Access 查询转换为 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52443444/

相关文章:

python - 编辑 python 包

python - 如果我有素数/指数列表,如何生成数字的所有乘法分区?

python - 如何在扭曲的 python 中从服务器发送列表中的内容?

scala - 使用 DataFrame 解析混合内容 XML

python - 如何在打开顶层时删除登录窗口?

mysql - 第 6 行的 SQL 语法错误

php - 如何通过 PHP 发送带有 SQL 信息的表

mysql - SQL 查询 : Separate column where IDs are the same but type is different

python - 从单列 Pandas 数据框生成词云

python - 合并 2 个 panda 数据帧,其中索引是字符串