pandas - 将选定的列和行组合在一起,对单元格的内容进行求和

问题描述 投票:0回答:1

如何将某些列和行合并在一起,以便合并单元格的值相加?

目前,我有一个大熊猫数据框,显示机场之间的航班数量。但是,我需要城市之间的航班数量。

我有一个字典,城市名称作为键,机场ID代码列表作为值。有没有办法可以合并与同一城市相关的机场的行和列?

词典:

{'Akron': ['AKC', 'CAK', 'AKO'],
 'Albany': ['ALB', 'ABY', 'ALH'],
 'Albuquerque': ['ABQ'],
 'Allentown': ['ABE'],
 'Atlanta': ['ATL', 'FTY', 'PDK', 'RYY', 'FFC'],
 'Austin': ['AUS'],
 'Baltimore': ['BWI', 'MTN'],
 'Baton Rouge': ['BTR'],
 ...
 # so on and so forth

交叉编号的航班号的数据帧段:

DEST    ABE  ABQ  ABY  ALB   ATL  AUS  AVP  BHM  BNA  
ORIGIN                                                  
ABE       0    0    0    0   128    0    1    0    0    
ABQ       0    0    0    0   181   24    0    4    0    
ABY       0    0    0    0    82    0    0    0    0    
ALB       0    0    0    0   196    4    0    0    1    
ATL     132  181   95  224     0  668   71  672  634    
AUS       0   20    0    0   655    0    0    1  116    
AVP       0    0    0    0    63    0    0    0    0    
BHM       0    3    0    0   640    0    0    0    4    
BNA       0    0    0    0   661  105    0    4    0 

我想生成这样的数据帧:

 DEST        Akron Albany Albuquerque Allentown Atlanta ....
 ORIGIN
 Akron         0     19       34         0         59     
 Albany       10      0        3        15         21     
 Albuquerque  13      3        0        14          3    
 Allentown     0     10       17         0          5    
 Atlanta      50     21       23         2          0    
 ...

非常感谢所有帮助,谢谢。

pandas
1个回答
1
投票

IIUC,从你的dict创建替换词典,replace列和索引与城市名称,然后我们做sum

s={'Akron': ['AKC', 'CAK', 'AKO'],
 'Albany': ['ALB', 'ABY', 'ALH'],
 'Albuquerque': ['ABQ'],
 'Allentown': ['ABE'],
 'Atlanta': ['ATL', 'FTY', 'PDK', 'RYY', 'FFC'],
 'Austin': ['AUS'],
 'Baltimore': ['BWI', 'MTN'],
 'Baton Rouge': ['BTR']}

s1=pd.Series(s).apply(pd.Series).stack().reset_index()

dicttoreplace=dict(zip(s1[0],s1['level_0']))


df.columns=pd.Series(df.columns).replace(dicttoreplace)
df.index=pd.Series(df.index).replace(dicttoreplace)

df.sum(axis=1,level=0).sum(level=0)
© www.soinside.com 2019 - 2024. All rights reserved.