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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-09 13:09:50 +0000
Seen: 8 times
Last updated: Jul 09 '23
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?