For example I want to convert this list containing ranges
x=[[1,4],
[6,7],
[9,9]]
to a boolean list
x=[False, True, True, True, True, False, True, True, False, True]
This is obviously possible using a for loop. However, I am looking for a other options that are faster and better (one-liners are welcome e.g. maybe a list comprehension). Ideally, I am looking for some way that could also be applicable to a pandas series.
CodePudding user response:
A hopefully efficient way using numpy:
low, high = np.array(x).T[:,:, None] # rearrange the limits into a 3d array in a convenient shape
a = np.arange(high.max() 1) # make a range from 0 to 9
print(((a >= low) & (a <= high)).any(axis=0))
CodePudding user response:
inds = [[i for i in range(a, b 1)] for a, b in x]
inds = [el for ar in inds for el in ar]
[i in inds for i in range(max(inds) 1)]
# [False, True, True, True, True, False, True, True, False, True]
OR
inds = pandas.Series([[i for i in range(a, b 1)] for a, b in x]).explode()
pandas.Series(numpy.arange(inds.max() 1)).isin(inds)
# 0 False
# 1 True
# 2 True
# 3 True
# 4 True
# 5 False
# 6 True
# 7 True
# 8 False
# 9 True
# dtype: bool