Pandas使用df中的值从df返回值

时间:2017-03-28 09:31:17

标签: python python-2.7 pandas dataframe

我有一个df:

Index    ColA    ColB    ...    Marker1    Marker2    Return
 t0       a0      b0     ...      t0        colA        a0
 t1       a1      b1     ...      t1        colB        b1
 t2       a2      b2     ...      t1        colZ        z1
 t3       a3      b3     ...      t3        colB        b3

如何使用广播获取返回列?逻辑是:

  • Marker1 =相关指数
  • Marker2 =相关列
  • Return =坐标中的值(Marker1,Marker2)

2 个答案:

答案 0 :(得分:3)

使用pd.DataFrame.lookup

df.assign(Return2=df.lookup(df.Marker1, df.Marker2))

      ColA ColB ColZ Marker1 Marker2 Return Return2
Index                                              
t0      a0   b0   z0      t0    ColA     a0      a0
t1      a1   b1   z1      t1    ColB     b1      b1
t2      a2   b2   z2      t1    ColZ     z1      z1
t3      a3   b3   z3      t3    ColB     b3      b3

设置

from io import StringIO
import pandas as pd

txt = """Index    ColA    ColB    ColZ   ...    Marker1    Marker2    Return
 t0       a0      b0     z0     ...      t0        ColA        a0
 t1       a1      b1     z1     ...      t1        ColB        b1
 t2       a2      b2     z2     ...      t1        ColZ        z1
 t3       a3      b3     z3     ...      t3        ColB        b3"""

df = pd.read_csv(StringIO(txt), delim_whitespace=True, index_col=0).drop('...', 1)

答案 1 :(得分:1)

您可以使用:

df['new'] = df.apply(lambda x: df.loc[x.Marker1,x.Marker2], axis=1)

更好lookup

df['new'] = df.lookup(df.Marker1, df.Marker2)