我有一个系列S
:
attr
first last visit
andrew alexander baseline abc
andrew alexander followup abc
bruce alexander baseline abc
bruce alexander followup xyz
fuzzy dunlop baseline xyz
fuzzy dunlop followup abc
和一个 DataFrame df
:
abc xyz
first last visit
andrew alexander baseline 1 7
andrew alexander followup 2 8
bruce alexander baseline 3 9
bruce alexander followup 4 10
fuzzy dunlop baseline 5 11
fuzzy dunlop followup 6 12
如何获得一个新系列S2
,其中对于S
中的每个索引,值都是从df
中选择的。如果我要使用循环,我会这样做:
lookup = pd.Series(index=S.index)
for ix, attr in S.iteritems():
lookup.loc[ix] = df.loc[ix, attr]
有没有更直接的方法来使用 pandas 函数来做到这一点?
结果应如下所示:
first last visit
andrew alexander baseline 1
andrew alexander followup 2
bruce alexander baseline 3
bruce alexander followup 10
fuzzy dunlop baseline 11
fuzzy dunlop followup 6
最佳答案
IIUC,您可以使用DataFrame.lookup() :
In [7]: pd.Series(df.lookup(s.index, s['attr']), index=df.index)
Out[7]:
first last visit
andrew alexander baseline 1
followup 2
bruce alexander baseline 3
followup 10
fuzzy dunlop baseline 11
followup 6
dtype: int64
如果s
是Series(不是DataFrame):
In [10]: pd.Series(df.lookup(s.index, s), index=df.index)
Out[10]:
first last visit
andrew alexander baseline 1
followup 2
bruce alexander baseline 3
followup 10
fuzzy dunlop baseline 11
followup 6
dtype: int64
关于python - 我怎样才能用一系列的 Pandas 查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49500510/