我怎么能用一个系列做这个pandas查找?

时间:2018-03-26 21:00:36

标签: python pandas

我有一个系列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

1 个答案:

答案 0 :(得分:3)

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是系列(不是数据框):

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