简体   繁体   中英

Index + Match equivalent for Pandas in Python

I have a dataframe containing a column with dates and a column with a list of stock prices. I want to print a message that reports the highest observed stock price along with the corresponding date it was observed. This problem in Excel would be solved by using a vlookup , index-match or a simple .offset(0,-1) function. What is the Python equivalent? I am not interested in creating a new column, but simply printing the date.

Example of my dataframe ( data_df ):

在此处输入图片说明

Snippet of my code:

    max1 = data_df.loc[:, ticker].max()
    max1_date = "test" #data_df.loc[data_df.idxmax(axis=0,skipna=True), 'Date']

    print("The highest stock price observed at: \n", ticker, ":", max1.round(2), "USD on the date ", max1_date
         )

where ticker is generated elsewhere in my code. In this example ticker is ATVI .

我通过设置解决了: max1_date = data_df[data_df[ticker] == max1]['Date'].values[0]

您可以使用带有nextiter DataFrame.loc来获取第一个匹配的值,如果值不匹配,则获取字符串no match

max1_date = next(iter(data_df.loc[data_df[ticker] == max1, 'Date']), 'no match')
data_df.iloc[data_df.ATVI.idxmax()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM