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
Excel VLOOKUP equivalent in pandas
提问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 B
consists of dates from column A
shifted forward by some. I would like to generate column C
that consists of the values from column A
on 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 B
and Index
is not always equal).
列B
由A
前移一些列的日期组成。我想生成C
由A
date列中的值组成的列B
。(最好是在逻辑中的Excel VLOOKUP公式会做到这一点。我不是在寻找简单的shift(-2)
这里,是因为在现实之间的转移B
和Index
并不总是等于)。
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 map
by 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