我想获取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向量中列的索引。我需要矩阵和向量匹配的索引。
答案 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)