python - NumPy 中的 Pandas Series.map 等价物

标签 python pandas numpy

我有一个查找值的字典dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 3}

我想从 numpy 得到的结果是 pandas.Series.map() 传入字典后返回的结果。例如 series.map(dictionary, na_action='ignore')

注意:这个 series.map() 函数非常快,这让我相信在 numpy API 中一定有一个等价物,而不是我实现一些涉及 numpy.where() 的解决方案 并循环遍历字典键。

最佳答案

这是一个 NumPy 的 -

def map_series_by_dict(s, d):
    a = s.values
    v = np.array(list(d.values()))
    k = np.array(list(d.keys()))    
    sidx = k.argsort()
    out_ar = v[sidx[np.searchsorted(k,a,sorter=sidx)]]
    return pd.Series(out_ar, index=s.index)

sample 运行-

In [143]: d
Out[143]: {'a': 1, 'b': 2, 'c': 3, 'd': 3}

In [144]: s
Out[144]: 
0    a
1    a
2    c
3    b
4    a
dtype: object

In [145]: map_series_by_dict(s, d)
Out[145]: 
0    1
1    1
2    3
3    2
4    1

关于python - NumPy 中的 Pandas Series.map 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52653043/

相关文章:

python - 使用 .index 在 pandas 中删除行

python-2.7 - 截断多索引数据帧

python - 第一次组在 Pandas DataFrame 中满足条件

python - 我可以使用 Numba、矢量化或多处理加速这种空气动力学计算吗?

python - pd.Timestamp 与 np.datetime64 : are they interchangeable for selected uses?

python - 如何减去两个无符号的 numpy 数组以给出带符号的结果?

python - Beautiful Soup 使用波斯字符串查找

python - 如何使用 .loc 通过 groupby pandas 标记新列

python - 根据总 str 长度选择字符串的中间部分到新列 pandas

python - 使用 Python 和 xlsxwriter 将单元格引用与单元格计数连接起来