简体   繁体   中英

Normalize each column of a pandas DataFrame

Each column of the Dataframe needs their values to be normalized according the value of the first element in that column.

for timestamp, prices in data.iteritems():
    normalizedPrices = prices / prices[0]
    print normalizedPrices     # how do we update the DataFrame with this Series?

However how do we update the DataFrame once we have created the normalized column of data? I believe if we do prices = normalizedPrices we are merely acting on a copy/view of the DataFrame rather than the original DataFrame itself.

It might be simplest to normalize the entire DataFrame in one go (and avoid looping over rows/columns altogether):

>>> df = pd.DataFrame({'a': [2, 4, 5], 'b': [3, 9, 4]}, dtype=np.float) # a DataFrame
>>> df
   a  b
0  2  3
1  4  9
2  5  4

>>> df = df.div(df.loc[0]) # normalise DataFrame and bind back to df
>>> df
     a         b
0  1.0  1.000000
1  2.0  3.000000
2  2.5  1.333333

Assign to data[col] :

for col in data:
    data[col] /= data[col].iloc[0]
import numpy

data[0:] = data[0:].values/data[0:1].values 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM