【问题标题】:How to apply function on a dataframe如何在数据框上应用函数
【发布时间】:2017-08-14 13:33:11
【问题描述】:

我有一个示例数据框(df):

                               Time             Price
Equity(231 [IBM])   2016-05-10 00:00:00+00:00  150.04
Equity(2574 [TSLA]) 2016-04-29 00:00:00+00:00  248.43

我想使用数据框中的值以及来自其他变量的值在每一行上应用函数 findy(),并将这些值存储在新列 Predicted 中。

我有这些变量(值是从输出中复制的):

high_1 = Equity(231 [IBM])      151.676
         Equity(2574 [TSLA])    258.310
         Equity(0 [AAPL])       111.710

idx_1 =  Equity(231 [IBM])     2016-04-18 00:00:00+00:00
         Equity(2574 [TSLA])   2016-04-18 00:00:00+00:00
         Equity(0 [AAPL])      2016-04-14 00:00:00+00:00

我想应用这个功能:

def findy(s,Time,Price,idx_1, high_1, idx_last):
    idx = [idx_1.loc[s.index], Time]
    x = matplotlib.dates.date2num(idx)
    y = [high_1.loc[s.index], Price]
    coefficients = np.polyfit(x, y, 1)
    polynomial = np.poly1d(coefficients)
    x_axis = np.linspace(x[0], idx_last + 1, 3)  # linspace(start, end, num)
    y_axis = polynomial(x_axis)
    return Predicted_Value

我尝试使用此代码:

df["Predicted"] = df.apply(lambda s: 
                          findy(s,s['Time'],s['Price'],idx_1,high_1,idx_last))

lambda 函数中,我试图获取每个股票的indexTimePrice 并插入函数并将这些值用于findy() 中的操作。 但是我遇到了像KeyError: ('Time', 'occurred at index Time')这样的错误 主要问题是坐在lambda 内部以及如何从行中访问值。

如果您想了解更多信息,请随时询问。

【问题讨论】:

  • 我认为你只需要在你的调用中添加一个额外的参数来应用。 df["Predicted"] = df.apply(lambda s: findy(s,s['Time'],s['Price'],idx_1,high_1,idx_last), 1) 会告诉它逐行应用。现在,它正在尝试逐列。
  • 你的意思是axis=1?我试过了,但我仍然得到错误。
  • 错误是相同还是不同?
  • @JCVanHamme 当我使用axis=1 时,它会引发KeyError: ("None of [Index(['Time', 'Price'], dtype='object')] are in the [index]", 'occurred at index Equity(231 [IBM])')
  • @ArJuN,你在哪里以及如何定义idx_1,high_1,idx_last

标签: python pandas numpy dataframe lambda


【解决方案1】:

问题出在您的findy 函数中。第一行尝试做idx_1.loc[s.index]s.index 的值类似于 Index(['Time', 'Price'], dtype='object')。然后它在idx_1 的索引中寻找['Time', 'Price'],但它并不存在。

我认为你必须重新评估你的findy 函数。即使第一行有效,您转身并将结果传递给matplotlib.dates.date2num,它期望datetimedatetimes 的序列。这不会是 idx 包含的内容。

【讨论】:

  • 感谢您的回答,但'Time','Price' 是列名,索引是Equity(231 [IBM]),请您多看一下,非常感谢。
  • 是的,'Time' 和 'Price' 是数据帧的列名,但是当您传入代表该帧行的系列对象时,它们将成为索引值。您应该仔细检查 s.index 在您的 findy 函数中的样子。
  • 嗯,有道理,我会找出来的。谢谢:)
猜你喜欢
  • 2020-04-21
  • 2016-07-10
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多