【发布时间】: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 函数中,我试图获取每个股票的index、Time、Price 并插入函数并将这些值用于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