0
1

Pandasで標準化と元に戻す方法

Last updated at Posted at 2024-08-07

pandasで標準化を元に戻すという意味のないことを考えてみました。
まず標準化の式はこうなので

t=\frac{x-μ}{σ}

元に戻すにはこうなります。

x=tσ+μ

では実際にやってみます

import pandas as pd

df = pd.read_csv("iris.csv")
df.drop("category", axis=1).describe()

image.png
※PCを変えたので画質が落ちています。

続いて標準化関数です。

def standard(x):
    val = {}
    for col in x.columns:
        val[col] = {"std" : x[col].std()}, {"mean" : x[col].mean()}
        x[col] = (x[col] - x[col].mean()) / x[col].std()
    return x, val

そして元に戻す関数です。

def reverse(x, val):
    for col in x.columns:
        x[col] = x[col] * val[col][0]["std"] + val[col][1]["mean"]
    return x

では実際に標準化と元に戻すのをやってみましょう。

x, val = standard(df.drop("category", axis=1))
x.describe()

image.png
標準化されました。
続いて元に戻します。

x = reverse(x, val)
x.describe()

image.png

というわけで元に戻りました。

まとめ

Pandasでやらないといけないときの参考に

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1