通过行求和来对pandas DataFrame进行归一化

49

如何规范化pandas DataFrame的每一行?规范化列很容易,因此一个(非常丑陋的!)选项是:

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

Pandas广播规则阻止了df / df.sum(axis=1)的实现。
2个回答

102

1
最好能够在管道中完成,而不需要先计算df。 - linello
3
df.pipe(lambda df: df.div(df.sum(axis=1), axis=0) 可以行得通吗? - joris

-4
我建议使用Scikit preprocessing库,并根据需要转置您的数据框:
'''
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()                                   

2
几乎所有的绘图代码都是无关紧要的,除了涉及到preprocessing.MinMaxScaler和相应的import的三行代码。你能把你的答案简化成那样吗? - smci

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接