I'm trying to create a basic function that takes three Series objects and returns a DataFrame with one column of values, similar to the example values below. The Series objects used as parameters in my function already include the dates within their indexes and look identical to the following data as well.
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
However, whenever I attempt to call my function, I receive this error, which is particularly confusing as my DataFrame already contains an index and I believe I am using assign()
correctly to create a new column.
TypeError: Indexing a Series with DataFrame is not supported, use the appropriate DataFrame column
Below is the culprit code in question.
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
What am I doing incorrectly in this situation? I am currently using Python 3.9.5
and Pandas 2.0.1
for my code.
The problem that the x
in pivot_df.assign(pivot=lambda x: (high[x] + low[x] + close[x])/3)
is the whole pivot_df
dataframe, and as the error message states, that doesn't work as an indexer.
A straight-forward fix is to use
pivot_df = pivot_df.assign(
pivot=lambda x: (high[x.index] + low[x.index] + close[x.index])/3
)
But I think the following is more elegant (everything will be joined on the common index):
pivot_df["pivot"] = (high + low + close)/3