Pandas 中的 Excel VLOOKUP 等效项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38291908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:33:08  来源:igfitidea点击:

Excel VLOOKUP equivalent in pandas

pythonpandas

提问by Al_Iskander

I have following dataframe:

我有以下数据框:

               A           B            C
 Index
2001-06-30    100       2001-08-31     (=value of A at date B)
2001-07-31    200       2001-09-30      ...
2001-08-31    300       2001-10-31      ...
2001-09-30    400       2001-11-30      ...

Column Bconsists of dates from column Ashifted forward by some. I would like to generate column Cthat consists of the values from column Aon date B. (preferably in the logic the Excel VLOOKUP formula would do it. I am not looking for simply shift(-2)here because in reality the shift between Band Indexis not always equal).

BA前移一些列的日期组成。我想生成CAdate列中的值组成的列B。(最好是在逻辑中的Excel VLOOKUP公式会做到这一点。我不是在寻找简单的shift(-2)这里,是因为在现实之间的转移BIndex并不总是等于)。

I tried df.loc['B', 'A']but this most probably too simplistic and produced an error.

我试过了,df.loc['B', 'A']但这很可能太简单了并产生了错误。

回答by jezrael

I think you need mapby column A:

我认为您需要map按列A

df['C'] = df.B.map(df.A)
print (df)
              A          B      C
Index                            
2001-06-30  100 2001-08-31  300.0
2001-07-31  200 2001-09-30  400.0
2001-08-31  300 2001-10-31    NaN
2001-09-30  400 2001-11-30    NaN

It is same as:

它与:

df['C'] = df.B.map(df.A.to_dict())
print (df)
              A          B      C
Index                            
2001-06-30  100 2001-08-31  300.0
2001-07-31  200 2001-09-30  400.0
2001-08-31  300 2001-10-31    NaN
2001-09-30  400 2001-11-30    NaN