So i've this sample dataframe:
x_mean x_min x_max y_mean y_min y_max
1 85.6 3 264 75.7 3 240
2 105.5 6 243 76.4 3 191
3 95.8 19 287 48.4 8 134
4 85.5 50 166 64.8 32 103
5 55.9 24 117 46.7 19 77
x_range = [list(range(0,50)),list(range(51,100)),list(range(101,250)),list(range(251,350)),list(range(351,430)),list(range(431,1000))]
y_range = [list(range(0,30)),list(range(31,60)),list(range(61,90)),list(range(91,120)),list(range(121,250)),list(range(251,2000))]
#here x = Any column with mean value (eg. x_mean or y_mean)
# y = x_range / y_range
def min_max_range(x,y):
for a in y:
if int(x) in a:
min_val = min(a)
max_val = max(a)+1
return max_val - min_val
def min_range(x,y):
for a in y:
if int(x) in a:
min_val = min(a)
return min_val
Now i want to apply these function min_max_range()
and min_range()
to column x_mean, y_mean
to get new columns.
Like the function min_max_val
is using column x_mean
& the range x_range
as the input to create column x_min_max_val
, similarly column y_mean
& the range y_range
are used for the column y_min_max_val
:
I can create each column one by one, by using these one liners, but i want to apply this to both column x_mean & y_mean
columns in one go with a one liner.
df['x_min_max_val'] = df['x_mean'].apply(lambda x: min_max_range(x,x_range))
df['y_min_max_val'] = df['y_mean'].apply(lambda x: min_max_range(x,y_range))
The resultant dataframe should look like this:
x_mean x_min x_max y_mean y_min y_max x_min_max_val y_min_max_val x_min_val y_min_val
1 85.6 3 264 75.7 3 240 49 29 51 61
2 105.5 6 243 76.4 3 191 149 29 101 91
3 95.8 19 287 48.4 8 134 49 29 51 91
4 85.5 50 166 64.8 32 103 49 29 51 61
5 55.9 24 117 46.7 19 77 49 29 51 31
I want to create these columns in one go, instead of creating one column ata time. How can i do this? Any suggestions? or something like this could work?
df.filter(regex='mean').apply(lambda x: min_max_range(x,x+'_range'))
See Question&Answers more detail:
os