I want to find a number in series
, and find which number it's closest to in [1,2,3]
. Then use the key
to replace the series value with the appropriate letter.
key = {1: 'A', 2:'B', 3:'C')
series = pd.Series([x*1.2 for x in range(10)])
pd.DataFrame = key[min([1,2,3], key=lambda x: abs(x-series))]
The series
is a column from the pd.DataFrame
, I've just tried to simplify it for here.
答案 0 :(得分:1)
use the apply
method and then map
your Series
such has:
key = {1: 'A', 2:'B', 3:'C'}
series = pd.Series([x*1.2 for x in range(10)])
def find(myNumber):
return min([1,2,3], key=lambda x:abs(x-myNumber))
series.apply(find).map(key)
Out[50]:
0 A
1 A
2 B
3 C
4 C
5 C
6 C
7 C
8 C
9 C
dtype: object
it also should work if you replace series by the entire dataframe such has:
df.apply(find).map(key)