我想要为DataFrame中的一些时间序列数据计算扩展的z得分,但我想使用多列的平均值和标准差来标准化数据,而不是使用每列中单独的平均值和标准差。我相信我想要使用groupby和DataFrame.expanding的组合,但我似乎无法弄清楚。以下是一些示例数据:
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()),但我不知道如何做后一件事。
我已经对groupby、stack()和expanding()的各种组合进行了大量实验,但都无济于事。
发布于 2017-07-12 09:05:09
这是我自己的尝试,试图计算所有列的扩展Z分数。欢迎就如何更有效地做这件事发表意见。
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 zScoreshttps://stackoverflow.com/questions/45044764
复制相似问题