python - 我怎样才能用一系列的 Pandas 查找?

标签 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

最佳答案

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/

相关文章:

调用函数时,Python 模块 audiolab 返回错误

python - 我如何知道网站的领域和 uri 是什么

python - 变换多项式图 - 乘以值列表

python - Pandas:遍历所有行的循环

python-3.x - 比较包含字符串的数据帧行

python - 合并 Pandas DataFrame 中多行的数据

python - 如何迭代 pandas 列中的列表以查找匹配项?

python - celery worker 挂起没有任何错误

python - Pandas Dataframe 保留日期在两个日期之间的行(单独的列)

python - 如何同时捕获和显示 ipython (jupyter notebook) 单元格输出?