【问题标题】:Z-score normalization in pandas DataFrame (python)pandas DataFrame(python)中的Z-score标准化
【发布时间】:2020-04-27 07:57:33
【问题描述】:

我正在使用 python3 (spyder),并且我有一个表,它是对象“pandas.core.frame.DataFrame”的类型。我想对该表中的值进行 z-score 标准化(每个值减去其行的平均值并除以其行的 sd),因此每行的均值 = 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

这两种方法似乎都有效,但是当我检查每行的平均值和标准差时,它不是假设的 0 和 1,而是其他浮点值。我不知道可能是哪个问题。

提前感谢您的帮助!

【问题讨论】:

    标签: python-3.x pandas spyder normalization


    【解决方案1】:

    以下代码为 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)
    

    【讨论】:

      【解决方案2】:

      抱歉,考虑一下,我发现自己计算 z-score 的另一种方法比 for 循环更简单(减去每行的平均值并将结果除以该行的 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,所以这对我有用。抱歉,我的编码经验很少,有时简单的事情需要进行大量试验,直到我弄清楚如何解决它们。

      【讨论】:

        猜你喜欢
        • 2021-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        • 2020-10-14
        • 2021-05-05
        相关资源
        最近更新 更多