Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

python - Excel VLOOKUP equivalent in pandas

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).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you need map by column 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...