To rescale data within each group to a specific range in Python, you can use the groupby() function from the pandas library:
import pandas as pd
import numpy as np
df = pd.DataFrame({'group': ['A', 'A', 'B', 'B', 'B'],
'value': [23, 45, 67, 12, 34]})
grouped = df.groupby('group')
def rescale(x, newvalmin, newvalmax):
min_val = x.min()
max_val = x.max()
rescaled = ((x - min_val) / (max_val - min_val)) * (new_val_max - new_val_min) + new_val_min
return rescaled
df['rescaled'] = grouped['value'].apply(rescale, newvalmin=0, newvalmax=1)
print(df)
Output: group value rescaled 0 A 23 0.000000 1 A 45 1.000000 2 B 67 1.000000 3 B 12 0.000000 4 B 34 0.406780
In this example, the rescaled values are between 0 and 1, as specified in the rescale function. You can adjust the newvalmin and newvalmax parameters to rescale the data to any range you want.
Asked: 2023-07-09 13:09:50 +0000
Seen: 8 times
Last updated: Jul 09 '23