获取第二个系列中第一个系列的元素索引

时间:2018-12-10 21:28:08

标签: python pandas indexing series

我想获取smaller系列的larger系列中所有值的索引。答案是存储在ans变量中的以下代码段。

import pandas as pd

smaller = pd.Series(["a","g","b","k"])
larger = pd.Series(["a","b","c","d","e","f","g","h","i","j","k","l","m"])

# ans to be generated by some unknown combination of functions
ans = [0,6,1,10]
print(larger.iloc[ans,])
print(smaller)
assert(smaller.tolist() == larger.iloc[ans,].tolist())

上下文:系列larger用作numpy矩阵中列的索引,而系列smaller用作numpy向量中列的索引。我需要矩阵和向量匹配的索引。

4 个答案:

答案 0 :(得分:2)

您可以颠倒larger系列,然后使用smaller将其编入索引:

larger_rev = pd.Series(larger.index, larger.values)
res = larger_rev[smaller].values

print(res)

array([ 0,  6,  1, 10], dtype=int64)

答案 1 :(得分:1)

    for i in list(smaller):
        if i in list(larger):
            print((list(larger).index(i)))

这将为您提供所需的输出

答案 2 :(得分:1)

使用Series get

pd.Series(larger.index, larger.values).get(smaller)
Out[8]: 
a     0
g     6
b     1
k    10
dtype: int64

答案 3 :(得分:0)

尝试:)

    import pandas as pd
    larger = pd.Series(["a","b","c","d","e","f","g","h","i","j","k","l","m"])
    smaller = pd.Series(["a","g","b","k"])

    res = pd.Series(larger.index, larger.values).reindex(smaller.values, copy=True)
    print(res)