복붙노트

[PYTHON] 판다 DataFrame을 행 단위로 정규화하기

PYTHON

판다 DataFrame을 행 단위로 정규화하기

pandas DataFrame의 각 행을 정규화하는 가장 관용적 인 방법은 무엇입니까? 열을 정규화하는 것이 쉽기 때문에 하나의 (매우 못생긴!) 옵션은 다음과 같습니다.

(df.T / df.T.sum()).T

팬더 방송 규칙에 따라 df / df.sum (축 = 1)이이 작업을 수행 할 수 없습니다.

해결법

  1. ==============================

    1.브로드 캐스트 문제를 극복하기 위해 div 메서드를 사용할 수 있습니다.

    브로드 캐스트 문제를 극복하기 위해 div 메서드를 사용할 수 있습니다.

    df.div(df.sum(axis=1), axis=0)
    

    http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior를 참조하십시오.

  2. ==============================

    2.Scikit 전처리 라이브러리를 사용하고 필요에 따라 데이터 프레임을 조 변경하는 것이 좋습니다.

    Scikit 전처리 라이브러리를 사용하고 필요에 따라 데이터 프레임을 조 변경하는 것이 좋습니다.

    '''
    Created on 05/11/2015
    
    @author: rafaelcastillo
    '''
    
    import matplotlib.pyplot as plt
    import pandas
    import random
    import numpy as np
    from sklearn import preprocessing
    
    def create_cos(number_graphs,length,amp):
        # This function is used to generate cos-kind graphs for testing
        # number_graphs: to plot
        # length: number of points included in the x axis
        # amp: Y domain modifications to draw different shapes
        x = np.arange(length)
        amp = np.pi*amp
        xx = np.linspace(np.pi*0.3*amp, -np.pi*0.3*amp, length)
        for i in range(number_graphs):
            iterable = (2*np.cos(x) + random.random()*0.1 for x in xx)
            y = np.fromiter(iterable, np.float)
            if i == 0: 
                yfinal =  y
                continue
            yfinal = np.vstack((yfinal,y))
        return x,yfinal
    
    x,y = create_cos(70,24,3)
    data = pandas.DataFrame(y)
    
    x_values = data.columns.values
    num_rows = data.shape[0]
    
    fig, ax = plt.subplots()
    for i in range(num_rows):
        ax.plot(x_values, data.iloc[i])
    ax.set_title('Raw data')
    plt.show() 
    
    std_scale = preprocessing.MinMaxScaler().fit(data.transpose())
    df_std = std_scale.transform(data.transpose())
    data = pandas.DataFrame(np.transpose(df_std))
    
    
    fig, ax = plt.subplots()
    for i in range(num_rows):
        ax.plot(x_values, data.iloc[i])
    ax.set_title('Data Normalized')
    plt.show()                                   
    
  3. from https://stackoverflow.com/questions/18594469/normalizing-a-pandas-dataframe-by-row by cc-by-sa and MIT license