从列表中的系列中查找值并返回匹配的索引

2024-04-25 15:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种不用循环的方法?你知道吗

我在想这样的事情:

pd_series = pd.Series(["c", "d", "a", "b"])
list_map  = ["a", "b", "c", "d"]
In [1]: pd_series.find_in(list_map)
Out [1]: 
0    2
1    3
2    0
3    1

谢谢!你知道吗


Tags: 方法inmapfindout事情listseries
2条回答

您可以使用np.vectorize+get_loc

np.vectorize(pd.Index(pd_series).get_loc)(list_map)
Out[499]: array([2, 3, 0, 1])

您可以使用实际地图而不是列表,假设元素是唯一的:

>>> actual_map = dict(zip(list_map, range(len(list_map))))
>>> actual_map
{'d': 3, 'b': 1, 'a': 0, 'c': 2}
>>> pd_series.map(actual_map)
0    2
1    3
2    0
3    1
dtype: int64

相关问题 更多 >