[英]Creating a column variable taking the mean of a variable conditional on two other variables
我有一個數據框,顯示每個給定條件的均值'dwdime'
:
DIMExCand_means = DIMExCand.groupby(['cycle', 'coded_state', 'party.orig', 'comtype']).mean()
我使用以下命令和輸出從DIMExCand_means創建了數據透視表:
DIMExCand_master = pd.pivot_table(DIMExCand_means,index=["Cycle","State"])
但是,在此過程中一些數據會丟失。 我想在'DIMExCand_master'
數據'DIMExCand_master'
添加列,其中包括給定'party.orig'
和'comptype'
每種可能組合的平均'dwdime'
得分,因為這將使我每個'cycle'-'coded_state'
有一個條目'cycle'-'coded_state'
。
我們試試吧:
DIMExCand_means = DIMExCand_means.reset_index()
DIMExCand_master = DIMExCand_master.reset_index()
pd.merge(DIMExCand_means, DIMExCand_master, left_on=['cycle','coded_state'], right_on=['Cycle','State'])
謝謝!
我最終選擇了:
DIMExCand_dime = pd.pivot_table(DIMExCand,值='dwdime',索引[“ Cycle”,“ State”],列='ID',aggfunc = np.mean)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.