I apply idxmin() to get the index of the minimum absolute value of two columns:
rep["OffsetFrom"] = rep[["OffsetDates", "OffsetDays"]].abs().idxmin(axis=1).dropna()
OffsetDates OffsetDays OffsetFrom
0 0.0 0.0 OffsetDates
1 1.0 1.0 OffsetDates
2 4.0 -3.0 OffsetDays
3 4.0 -3.0 OffsetDays
4 6.0 -1.0 OffsetDays
... ... ... ...
1165 0.0 0.0 OffsetDates
1166 0.0 0.0 OffsetDates
1167 0.0 0.0 OffsetDates
1168 0.0 0.0 OffsetDates
1169 0.0 0.0 OffsetDates
1170 rows × 3 columns
How do I get a column of the actual values after that?
PS. This one wouldn't work, since I need to keep the original signs:
rep[["OffsetFrom", "Offset"]] = rep[["OffsetDates", "OffsetDays"]].abs().agg(['idxmin','min'], axis=1)
Edit:
Eventually, I've simply done it with apply:
def get_abs_min_keep_sign(x):
return min(x.min(), x.max(), key=abs)
rep["Offset"] = rep[["OffsetDates", "OffsetDays"]].apply(get_abs_min_keep_sign, axis=1)
However, there must be a more elegant approach out there.