[英]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. 此问题在Excel中会使用来解决vlookup
, index-match
或简单.offset(0,-1)
的功能。 What is the Python equivalent? 什么是Python等价物? I am not interested in creating a new column, but simply printing the date. 我对创建新列不感兴趣,而只是打印日期。
Example of my dataframe ( data_df
): 我的数据data_df
( 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. ticker
在其他地方生成的地方。 In this example ticker is ATVI . 在此示例中,股票代码为ATVI 。
我通过设置解决了: max1_date = data_df[data_df[ticker] == max1]['Date'].values[0]
您可以使用带有next
和iter
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()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.