Python 减去数据帧中参数特定的列平均值

Python 减去数据帧中参数特定的列平均值,python,pandas,dataframe,Python,Pandas,Dataframe,我想通过使用Panda Dataframe计算并减去特定于参数(这里是特定于行业的)的列的平均值 我的数据如下: NAT SEC 2006 2007 2008 AUS D01T03 6750.0 7138.0 ... AUS D09 4926.0 6092.0 ... AUT D01T03 4926.0 5969.0 ... AUT D09 3381.0 3310.0 ... BEL D01T03 11733.0 12883.0

我想通过使用Panda Dataframe计算并减去特定于参数(这里是特定于行业的)的列的平均值

我的数据如下:

NAT SEC     2006    2007    2008
AUS D01T03  6750.0  7138.0  ... 
AUS D09     4926.0  6092.0  ... 
AUT D01T03  4926.0  5969.0  ... 
AUT D09     3381.0  3310.0  ... 
BEL D01T03  11733.0 12883.0 ... 
BEL D09     1938.0  1937.0  ...
TYP     SEC     2006    2007    ...
Mean    D01T03  7803.0  8663.3  ...
Mean    D09     3415.0  4049.6  ...
现在我想单独或直接(尽可能)计算
SEC
列中两个参数的平均值,如下所示:

NAT SEC     2006    2007    2008
AUS D01T03  6750.0  7138.0  ... 
AUS D09     4926.0  6092.0  ... 
AUT D01T03  4926.0  5969.0  ... 
AUT D09     3381.0  3310.0  ... 
BEL D01T03  11733.0 12883.0 ... 
BEL D09     1938.0  1937.0  ...
TYP     SEC     2006    2007    ...
Mean    D01T03  7803.0  8663.3  ...
Mean    D09     3415.0  4049.6  ...
在最后一步中,我想从“原始”数据帧中减去这个(在本例中是特定于行业的)平均值。因此,它可能看起来像这样:

NAT SEC     2006    2007    2008
AUS D01T03  -1053.0 ... ...
AUS D09     1511.0  ... ...
AUT D01T03  -2877.0 ... ...
AUT D09     -34.0   ... ...
BEL D01T03  3930.0  ... ...
BEL D09     -1477.0 ... ...
不幸的是,我没有找到任何合适的线程,直到现在,将非常高兴,如果有人能在这里帮助我或转发合适的线程!提前谢谢你

致意 Alex

IIUC,和的组合应该足够了

#set SEC as index
df = df.set_index('SEC').sort_index()

#aggregate the mean by the index
aggregation = df.groupby(level=0).mean()

#get the numeric only columns
num_cols = df.filter(regex='\d').columns

#assign the difference between the numeric columns and the aggregates back to the dataframe
df.loc[:,num_cols] = df.filter(regex='\d').sub(aggregation)

#sort by NAT 
df = df.sort_values('NAT')

df

        NAT 2006    2007
SEC         
D01T03  AUS -1053.0 -1525.333333
D09     AUS 1511.0  2312.333333
D01T03  AUT -2877.0 -2694.333333
D09     AUT -34.0   -469.666667
D01T03  BEL 3930.0  4219.666667
D09     BEL -1477.0 -1842.666667