Stack Overflow Asked on November 16, 2021
I have following dataframe. Values are the rating by customer.
Ind Department Value1 Value2 Value3 Value4
1 Electronics 5 4 3 2
2 Clothing 4 3 2 1
3 Grocery 3 3 5 1
Here I would like to make column range that is the difference of the max and min value from the row. Expected is as below:
Ind Department Value1 Value2 Value3 Value4 range
1 Electronics 5 4 3 2 3
2 Clothing 4 3 2 1 3
3 Grocery 3 3 5 1 3
df['range'] = df.max(axis=1) - df.min(axis=1)
If you want to specify column numbers to calculate the range:
df['range'] = df.iloc[:,col1index:col2index].max(axis=1) - df.iloc[:,col1index:col2index].min(axis=1)
Answered by ChairNTable on November 16, 2021
Filter for only the Values
column and compute the difference of the max and min per row :
boxes = df.filter(like="Value")
df["range"] = boxes.max(1) - boxes.min(1)
df
Ind Department Value1 Value2 Value3 Value4 range
0 1 Electronics 5 4 3 2 3
1 2 Clothing 4 3 2 1 3
2 3 Grocery 3 3 5 1 4
Same end result, but longer route, in my opinion - set the first two columns as index, get the difference of the max and min for each row, and reset the index :
(df
.set_index(["Ind", "Department"])
.assign(max_min=lambda x: x.max(1) - x.min(1))
.reset_index()
)
Answered by sammywemmy on November 16, 2021
You can try numpy
ptp
np.ptp(df.loc[:,'Value1':].values,axis=1)
array([3, 3, 4], dtype=int64)
df['range']=np.ptp(df.loc[:,'Value1':].values,axis=1)
Answered by BENY on November 16, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP