Scaling pandas series

Viewed 258

I'm doing a calculation on a DataFrame and then want to scale the results. I keep getting errors about expecting a 2D array and to "Reshape your data either using array.reshape(-1, 1) if your data has a single feature"

        import pandas as pd
        df = pd.DataFrame({'a': ['aaa', 'bbb', 'ccc'],
                           'b': [1, 2, 3],
                           'c': [4, 5, 6],
                           'd': [7, 8, 9]})
        df.set_index('a', inplace=True)

        series = df[['b', 'c']].sum(axis=1).div(df[['b', 'd']].sum(axis=1), axis=0)

        scaler = StandardScaler()
        series.values = scaler.fit_transform(series.values) 

I'm expecting a resulting DataFrame or Series with the original index intact and a single column of scaled results.

1 Answers

If it is one dimensional, you need to reshape it.. To avoid converting back and forth, you can do this (maybe there are better solutions):

series = pd.DataFrame({'values':series})

    values
a   
aaa 0.625
bbb 0.700
ccc 0.750

series['values'] = scaler.fit_transform(series[['values']])

    values
a   
aaa -1.297771
bbb 0.162221
ccc 1.135550
Related