在Python中的列中应用多个函数(Mean。,STD等)

时间:2017-12-06 14:47:09

标签: python pandas

我有4列8行的数据......

ServicePath="AmericanAppleServices.asmx"

我想在列而不是行中取A列和C列的均值和STD。例如,2和7的平均值和STD是"" (意思是)和" 3.535533906" (STD)分别如下。

我希望我的结果看起来像这样......

df = pd.DataFrame([[1, 2, 3,7], [2, 8, 6,8],[3, 2, 3,7], [4, 4, 6,8],[5, 2, 3,7], [6, 1, 6,8],[7, 8, 3,7], [8, 9, 6,8]], columns=['time','A', 'B', 'C'])

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

然而,当我尝试做

Mean STD 0 4.7 3.535533906 1 8 0 2 . . 3 . . . . . . . .

我收到以下错误...

AttributeError:' DataFrame'对象没有属性'时间'

我也试图通过这样做找到解决方案,但徒劳无功:

df= df.loc[(df.time>=2) & (df.time<=7),['A','C']],(['mean','std'])

但它给出了所有行均值和STD的结果。

df= df.loc[(df.time>=2) & (df.time<=7),['A','C']].agg(['mean','std'])

我该如何解决?

2 个答案:

答案 0 :(得分:3)

另一种方式:

In [347]: df[['Mean','STD']] = df[['A','C']].T.agg(['mean','std']).T

In [348]: df
Out[348]:
   time  A  B  C  Mean       STD
0     1  2  3  7   4.5  3.535534
1     2  8  6  8   8.0  0.000000
2     3  2  3  7   4.5  3.535534
3     4  4  6  8   6.0  2.828427
4     5  2  3  7   4.5  3.535534
5     6  1  6  8   4.5  4.949747
6     7  8  3  7   7.5  0.707107
7     8  9  6  8   8.5  0.707107

或作为原始DF中的新列:

www.google-analytics.com/analytics.js

答案 1 :(得分:1)

您可以使用describe

df[['A','C']].T.describe().T[['mean','std']]
Out[865]: 
   mean       std
0   4.5  3.535534
1   8.0  0.000000
2   4.5  3.535534
3   6.0  2.828427
4   4.5  3.535534
5   4.5  4.949747
6   7.5  0.707107
7   8.5  0.707107