我正在使用python3 (spyder),我有一个表,它是对象"pandas.core.frame.DataFrame“的类型。我想对该表中的值进行z-score归一化(每个值减去其所在行的平均值,再除以该行的sd ),这样每一行都有mean=0和sd=1。我尝试了两种方法。
第一种方法
from scipy.stats import zscore
zetascore_table=zscore(table,axis=1)
第二种方法
rows=table.index.values
columns=table.columns
import numpy as np
for i in range(len(rows)):
for j in range(len(columns)):
table.loc[rows[i],columns[j]]=(table.loc[rows[i],columns[j]] - np.mean(table.loc[rows[i],]))/np.std(table.loc[rows[i],])
table
这两种方法似乎都有效,但当我检查每一行的平均值和sd时,它不是假设的0和1,而是其他浮点值。我不知道哪一个是问题所在。
提前感谢您的帮助!
发布于 2021-02-27 06:51:43
下面的代码为pandas df列中的每个值计算z得分。然后,它将z得分保存在一个新列中(这里称为'num_1_zscore')。这很容易做到。
from scipy.stats import zscore
import pandas as pd
# Create a sample df
df = pd.DataFrame({'num_1': [1,2,3,4,5,6,7,8,9,3,4,6,5,7,3,2,9]})
# Calculate the zscores and drop zscores into new column
df['num_1_zscore'] = zscore(df['num_1'])
display(df)
发布于 2020-01-10 05:14:15
很抱歉,考虑到这一点,我找到了另一种比for循环更简单的计算z-score的方法(减去每一行的平均值,并将结果除以该行的sd ):
table=table.T# need to transpose it since the functions work like that
sd=np.std(table)
mean=np.mean(table)
numerator=table-mean #numerator in the formula for z-score
z_score=numerator/sd
z_norm_table=z_score.T #we transpose again and we have the initial table but with all the
#values z-scored by row.
我检查了一下,现在每行的平均值是0或非常接近0,sd是1或非常接近1,所以这对我来说是有效的。对不起,我几乎没有编码经验,有时简单的事情需要很多试验,直到我找到解决它们的方法。
https://stackoverflow.com/questions/59668597
复制相似问题