【问题标题】:Pandas - Python - Lookup functions - Need walk throughPandas - Python - 查找函数 - 需要遍历
【发布时间】:2021-06-18 12:08:04
【问题描述】:

我在创建两个看起来很简单的函数时遇到了麻烦,但是,我不断收到错误消息。

我有一个包含几列的数据框 (df),其中包括“股票”和“收盘价”,“股票”是股票代码的列表,“收盘价”是股票代码的收盘价。数据中有十个左右的代码,收盘价可以追溯到几个月前(总行数 = 1000)。

问题 1:具有两个参数的函数:“df”是一个数据框,“price”是一个浮点数。
任务:全部返回(不打印)收盘价低于“价格”的数据
我的代码:

def get_high_low_close(df, symbol):
    '''
    Get highest and lowest close price of a stock.
    Parameters
    df: Pandas DataFrame containing data from Problem 1's solution
    symbol: stock symbol
    Returns
    returns two values, highest and lowest close price of the stock.
    '''
    symbol = df[df.stock =='AA']

    result = symbol.groupby('stock').agg({'close': ['max', 'min']})

get_high_low_close(df,symbol)

我的输出: 关闭
最大最小值 库存
AA 17.92 14.72

我的输出值是正确的,但我收到以下消息:AssertionError: None != (17.92,14.72)。我的教授说我不需要使用 groupby 并且应该使用参数符号来选择行,但我仍然感到困惑。

我的第二个问题类似,使用相同的数据:
问题 2:具有两个参数的函数:“df”是一个数据框,“symbol”是一个字符串。
任务:返回(不打印)由符号表示的股票的最高和最低收盘价。'

我尝试了许多不同的代码,但无法得到答案。任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 您应该尝试使用 code 格式化更好地格式化您的代码

标签: python pandas function lookup


【解决方案1】:

您的问题需要更清晰,例如 df.head()。我会用一个例子来做一些假设来帮助解决问题

#reconstructing your question and making use of assumptions

#symbol
symbol = 'GOOGL'

df = pd.read_csv(symbol+'.csv')


def get_high_low_close(df, symbol):
    '''
    Get highest and lowest close price of a stock.
    Parameters
    df: Pandas DataFrame containing data from Problem 1's solution
    symbol: stock symbol
    Returns
    returns two values, highest and lowest close price of the stock.
    '''
    #highest close price
    highest_close_price = df['Close'].max()
    #lowest closing price
    lowest_close_price = df['Close'].min()
    
    #return them
    return highest_close_price, lowest_close_price
    

get_high_low_close(df,symbol)

#prints (2118.6201170000004, 1054.130005)

#price
price = 1115.47859

def get_high_low_close(df, symbol):
    '''
    Get highest and lowest close price of a stock.
    Parameters
    df: Pandas DataFrame containing data from Problem 1's solution
    symbol: stock symbol
    Returns
    returns two values, highest and lowest close price of the stock.
    '''
    #create function to evaluate the price
    def close_price(cls_price):
        if cls_price < price:
            return price
        
    #use apply function to evaluate the closing prices
    close_lower_than_price = df['Close'].apply(lambda x: close_price(x))
    close_lower_than_price = close_lower_than_price.dropna(how = "any") #drop nan values
    
    return close_lower_than_price

get_high_low_close(df, symbol)

返回低于价格的收盘价

 """
    0    1115.47859
    2    1115.47859
    4    1115.47859
    7    1115.47859
    9    1115.47859
    """

【讨论】:

  • 山姆,这太完美了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
相关资源
最近更新 更多