Find the nearest number(but not exceed) in the list and change numbers in the series(Python)
Question:
there is a series like below
s = pd.Series([25, 33, 39])
0 25
1 33
2 39
dtype: int64
and a list
list = [5, 10, 20, 26, 30, 31, 32, 35, 40]
[5, 10, 20, 26, 30, 31, 32, 35, 40]
I’d like to find the nearest number in the list and **change the number **in the series
for example
first number is the series is 25
but the list is [5, 10, 20, 26, 30, 31, 32, 35, 40]
so the firtst nearest number(corresponding to 25 in the series)
is 20 (Actually 26 is nearest number, but I need a number less than 25)
and then the second number is 31, thrid is 35
after finding the number and change that in the series
desired out s is
0 20
1 31
2 35
please give me advice. It’s a very important task for me.
if possilbe? without for loop plz
Find the nearest number(but not exceed) in the list and change numbers in the series(Python)
Answers:
You are looking for merge_asof
:
s = pd.Series([25, 33, 39], name="s")
l = pd.Series([5, 10, 20, 26, 30, 31, 32, 35, 40], name="l")
pd.merge_asof(s, l, left_on="s", right_on="l")
A few notes:
- There is a bug in your expected output. The closest number to 33 is 32.
- Don’t name your variable
list
. It overwrites the name of a very common Python class.
- Make sure
l
is sorted.
there is a series like below
s = pd.Series([25, 33, 39])
0 25
1 33
2 39
dtype: int64
and a list
list = [5, 10, 20, 26, 30, 31, 32, 35, 40]
[5, 10, 20, 26, 30, 31, 32, 35, 40]
I’d like to find the nearest number in the list and **change the number **in the series
for example
first number is the series is 25
but the list is [5, 10, 20, 26, 30, 31, 32, 35, 40]
so the firtst nearest number(corresponding to 25 in the series)
is 20 (Actually 26 is nearest number, but I need a number less than 25)
and then the second number is 31, thrid is 35
after finding the number and change that in the series
desired out s is
0 20
1 31
2 35
please give me advice. It’s a very important task for me.
if possilbe? without for loop plz
Find the nearest number(but not exceed) in the list and change numbers in the series(Python)
You are looking for merge_asof
:
s = pd.Series([25, 33, 39], name="s")
l = pd.Series([5, 10, 20, 26, 30, 31, 32, 35, 40], name="l")
pd.merge_asof(s, l, left_on="s", right_on="l")
A few notes:
- There is a bug in your expected output. The closest number to 33 is 32.
- Don’t name your variable
list
. It overwrites the name of a very common Python class. - Make sure
l
is sorted.