Skip to main content
 首页 » 编程设计

python之如何将每列的平均值转换为行

2024年12月31日8zhengyun_ustc

我是 Python 的新手,当您将列作为值添加并在行中添加值时,我需要您的帮助来获取结果。

这是一个例子:

列

A   B   C 
1   2   3 
4   5   6 
7   8   9 

预期结果:

   avg 
A   4 
B   5 
C   6 

我可以在 excel 中轻松完成,方法是将列放在“值”中,然后移动行中的值以获得平均值,但我似乎无法在 python 中完成。

请您参考如下方法:

df=pd.DataFrame({'A':[1,4,7],'B':[2,5,8],'C':[3,6,9]}) 
df 
   A  B  C 
0  1  2  3 
1  4  5  6 
2  7  8  9 
 
ser=df.mean()    #Result is a Series 
df=pd.DataFrame({'avg':ser})   #Convert this Series into DataFrame 
df  
   avg 
A  4.0 
B  5.0 
C  6.0