[英]How to use groupby, select, count(*) and where commands of SQL together in Pandas
我是在 python 中編寫 SQL 查詢的新手。
我有一個像這樣的 SQL 查詢。
select Category, Date, count(*) as Uniq, sum(FCnt) as Total,
sum(FCnt)/count(*) as RepRatio, Mod,Act,Exp, Sel,
Bias,Sel_B,Bias_B,Bias_P,Con_Num, Sel_Str,CG_D,CGM,TC,P_Value from
FCntt_Table where Sel_B=Bias_B group by
Mod,Act,Exp,Bias_P,Con_Num,CG_D order by RepRatio desc, Uniq desc;
我正在嘗試將此查詢轉換為 python 代碼,以便我可以使用 python 執行此查詢完成的操作。 我遇到了使用 Pandas 的選項。
我有 SQL 表 as.csv 格式。
我寫的代碼是
import pandas as pd
import numpy as np
tips=pd.read_csv("fc.csv")
tips["Total"]=tips.groupby(['Mod','Act','Exp','Bias_P','Con_Num','CG_D'])["FCnt"].transform("sum")
tips[tips['Sel_B'] == tips['Bias_B']]
print tips.groupby(['Mod','Act','Exp','Bias_P','Con_Num','CG_D']).agg({'Uniq':np.size})
print tips.head(5)
但這給了我 Uniq 的錯誤。 請幫助我使用此代碼。
示例數據:(由 OP 在評論中提供)
Date,Category,FCnt,TC,Mod,Con_Num,SC,Sel_P,Bias_P,Sel_B,Bias_B,Act,Exp,CG_D,CGM,P_val
20200622,T1,5,RE,649,SB3,01,0,0,0,1,0,GP2,cg1,0,Pattern1
20200622,T1,1,RE,649,SB3,10,1,0,0,1,0,GP2,cg2,0,pattern2
20200622,T1,4,RE,649,SB3,11,0,0,0,1,0,GP2,cg1,0,pattern1
20200622,T1,4,RE,649,SB3,11,1,0,0,1,0,GP2,cg1,0,pattern1
由於您想獲取組的總和和計數,我以不同的方式使用了聚合 function ,即.agg({'FCnt':(np.sum, np.size)})
。
代碼:
tips=pd.read_clipboard(sep=',')
# filtered_tips = tips[tips['Sel_B'] == tips['Bias_B']] # In given sample data, there is zero records after filter.
# So, considering original df
tips.groupby(['Mod','Act','Exp','Bias_P','Con_Num','CG_D']).agg({'FCnt':(np.sum,np.size)})
tips.columns = ['Total', 'Count']
Output:
print(group_df.reset_index())
Mod Act Exp Bias_P Con_Num CG_D Total Count
0 649 0 GP2 0 SB3 cg1 13 3
1 649 0 GP2 0 SB3 cg2 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.