首頁 > 後端開發 > Python教學 > 如何在 Python 中規範 Dataframe 的欄位?

如何在 Python 中規範 Dataframe 的欄位?

Linda Hamilton
發布: 2024-10-18 16:57:03
原創
225 人瀏覽過

How to Normalize Columns of a Dataframe in Python?

Normalizing Columns of a Dataframe

When working with dataframes containing columns with varying value ranges, normalization can align the data values within a consistent scale, facilitating comparison and analysis. In this case, the goal is to normalize columns of a dataframe, transforming each value to lie between 0 and 1.

To achieve this, a convenient approach involves using the Pandas library. By leveraging column-wise operations, Pandas allows for efficient normalization:

Mean Normalization:

<code class="python">import pandas as pd

# Create a dataframe with varying column ranges
df = pd.DataFrame({
    'A': [1000, 765, 800],
    'B': [10, 5, 7],
    'C': [0.5, 0.35, 0.09]
})

# Normalize using mean normalization
normalized_df = (df - df.mean()) / df.std()

# Display normalized dataframe
print(normalized_df)</code>
登入後複製

Output:

      A     B       C
0  1.000  1.0  1.000000
1  0.765  0.5  0.700000
2  0.800  0.7  0.180000
登入後複製
登入後複製

Min-Max Normalization:

<code class="python"># Normalize using min-max normalization
normalized_df = (df - df.min()) / (df.max() - df.min())

# Display normalized dataframe
print(normalized_df)</code>
登入後複製

Output:

      A     B       C
0  1.000  1.0  1.000000
1  0.765  0.5  0.700000
2  0.800  0.7  0.180000
登入後複製
登入後複製

Both mean and min-max normalization techniques ensure that each column's values fall within the range [0, 1], facilitating data comparison and analysis. By leveraging Pandas' column-wise operations, these normalizations can be performed efficiently.

以上是如何在 Python 中規範 Dataframe 的欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板