python - 数据帧非零列的平均值和标准差

标签 python numpy pandas

我有一个包含几列的数据框,每列都有一些正值、负值和零值。对于每一列,我想计算 x+y,其中 x 和 y 是每列绝对非零值的平均值和标准差。如何在 python 中执行此操作?

最佳答案

您可以使用 bool 条件过滤 df,然后迭代 cols 并调用 describe 并访问平均值和标准列:

In [103]:

df = pd.DataFrame({'a':np.random.randn(10), 'b':np.random.randn(10), 'c':np.random.randn(10)})
df
Out[103]:
          a         b         c
0  0.566926 -1.103313 -0.834149
1 -0.183890 -0.222727 -0.915141
2  0.340611 -0.278525 -0.992135
3  0.380519 -1.546856  0.801598
4 -0.596142  0.494078 -0.423959
5 -0.064408  0.475466  0.220138
6 -0.549479  1.453362  2.696673
7  1.279865  0.796222  0.391247
8  0.778623  1.033530  1.264428
9 -1.669838 -1.117719  0.761952
In [111]:

for col in df[df>0]:
    print('col:', col, df[col].describe()[['mean','std']])
col: a mean    0.028279
std     0.836804
Name: a, dtype: float64
col: b mean   -0.001648
std     1.014950
Name: b, dtype: float64
col: c mean    0.297065
std     1.159999
Name: c, dtype: float64

关于python - 数据帧非零列的平均值和标准差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29624726/

相关文章:

python - numpy.where : TypeError: invalid type promotion

python - 在特定索引之后将值添加到数据框列

python - 如何对齐重叠图中的直方图 bin 边缘

python - 使用总和为常数的 N 个随机数创建类泊松分布 (C)

python - 处理 numpy 数组中选定范围的值

python - df.loc[anything].index 和 iloc 有什么不同?

python - 在前台或后台运行 Twisted 应用程序的正确方法

python - 从 Python 中的切片对象中检索切片的长度

python - 基于另一列在 pandas 数据框中创建一列

python - 如何使用 epoll 和 python 3.1 进行异步 http 请求