首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Pandas -跨多列扩展Z-Score

Pandas -跨多列扩展Z-Score
EN

Stack Overflow用户
提问于 2017-07-12 05:28:11
回答 1查看 1.1K关注 0票数 0

我想要为DataFrame中的一些时间序列数据计算扩展的z得分,但我想使用多列的平均值和标准差来标准化数据,而不是使用每列中单独的平均值和标准差。我相信我想要使用groupby和DataFrame.expanding的组合,但我似乎无法弄清楚。以下是一些示例数据:

代码语言:javascript
运行
复制
import pandas as pd
import numpy as np
np.random.seed(42)

df = pd.DataFrame(np.random.rand(5,5),
                  columns=list('ABCDE'),
                  index=pd.date_range('2016-12-31', periods=5))

df.index.name = 'DATE'

df

输入:

所需输出:

我将行中的日期和数据系列作为单独的列。我想要的是一个与我计算扩展Z分数的形状相同的新DataFrame。我不知道如何让df.expanding(2).mean()方法跨多个列进行聚合。也就是说,不是取A列的扩展平均值,然后从A列的值中减去它,我想取A到E列中的值的扩展平均值,然后从A中的值中减去这些平均值。

如果你从Excel的角度来看,我所说的是=AVERAGE(B$2:B3)=AVERAGE($B$2:$F3)之间的区别。做前一件事非常简单(df.expanding(2).mean()),但我不知道如何做后一件事。

我已经对groupbystack()expanding()的各种组合进行了大量实验,但都无济于事。

EN

Stack Overflow用户

发布于 2017-07-12 09:05:09

这是我自己的尝试,试图计算所有列的扩展Z分数。欢迎就如何更有效地做这件事发表意见。

代码语言:javascript
运行
复制
def pooled_expanding_zscore(df, min_periods=2):
"""Calculates an expanding Z-Score down the rows of the DataFrame while pooling all of the columns.

Assumes that indexes are not hierarchical.
Assumes that df does not have columns named 'exp_mean' and 'exp_std'.
"""

# Get last sorted column name
colNames = df.columns.values
colNames.sort()
lastCol = colNames[-1]

# Index name
indexName = df.index.name

# Normalize DataFrame
df_stacked = pd.melt(df.reset_index(),id_vars=indexName).sort_values(by=[indexName,'variable'])

# Calculates the expanding mean and standard deviation on df_stacked
# Keeps just the rows where 'variable'==lastCol
df_exp = df_stacked.expanding(2)['value']
df_stacked.loc[:,'exp_mean'] = df_exp.mean()
df_stacked.loc[:,'exp_std'] = df_exp.std()

exp_stats = (df_stacked.loc[df_stacked.variable==lastCol,:]
            .reset_index()
            .drop(['index','variable','value'], axis=1)
            .set_index(indexName))

# add exp_mean and exp_std back to df
df = pd.concat([df,exp_stats],axis=1)

# Calculate Z-Score
df_mat = df.loc[:,colNames].as_matrix()
exp_mean_mat = df.loc[:,'exp_mean'].as_matrix()[:,np.newaxis]
exp_std_mat = df.loc[:,'exp_std'].as_matrix()[:,np.newaxis]
zScores = pd.DataFrame(
    (df_mat - exp_mean_mat) / exp_std_mat,
    index=df.index,
    columns=colNames)

# Use min_periods to kill off early rows
zScores.iloc[:min_periods-1,:] = np.nan

return zScores
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45044764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档