我正在尝试创建一个基本函数,它接受三个 Series 对象并返回一个包含一列值的 DataFrame,类似于下面的示例值。在我的函数中用作参数的 Series 对象已在其索引中包含日期,并且看起来也与以下数据相同。
Date
2022-04-26 4.500
2022-04-27 4.460
2022-04-28 4.540
2022-04-29 4.750
2022-05-02 4.340
...
2023-04-20 4.045
2023-04-21 3.990
2023-04-24 3.950
2023-04-25 3.840
2023-04-26 3.880
但是,每当我尝试调用我的函数时,我都会收到此错误,这特别令人困惑,因为我的 DataFrame 已经包含索引,并且我相信我正确使用
assign()
来创建新列。
TypeError: Indexing a Series with DataFrame is not supported, use the appropriate DataFrame column
下面是有问题的罪魁祸首代码。
def standard_pivot(high: pd.Series, low: pd.Series, close: pd.Series) -> pd.DataFrame:
"""
Returns a `DataFrame` object containing the standard pivot point column.
"""
date_arr = close.index.tolist()
pivot_df = pd.DataFrame(index=date_arr)
pivot_df = pivot_df.assign(pivot=lambda x: (high[x] + low[x] + close[x])/3)
return pivot_df
在这种情况下我做错了什么?我目前正在使用 Python
3.9.5
和 Pandas 2.0.1
作为我的代码。对于给您带来的不便,我深表歉意,并提前感谢您。
x
中的pivot_df.assign(pivot=lambda x: (high[x] + low[x] + close[x])/3)
是整个pivot_df
数据帧的问题,并且正如错误消息所述,它不能用作索引器。
一个直接的修复方法是使用
pivot_df = pivot_df.assign(
pivot=lambda x: (high[x.index] + low[x.index] + close[x.index])/3
)
但我认为以下更优雅(所有内容都将连接到公共索引上):
pivot_df["pivot"] = (high + low + close)/3