为何无法在DataFrame的lambda计算中使用Series值?
问题:使用Pandas创建枢轴点DataFrame时出现TypeError
问题背景
我尝试创建一个基础函数,接收三个索引为日期的pd.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
调用函数时出现以下错误:
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
错误原因
在assign的lambda函数里,参数x是当前的空DataFramepivot_df,你用high[x]试图用DataFrame去索引Series,而Pandas不允许用DataFrame对象作为Series的索引,这就是报错的核心原因。
修复方案
方法一:利用Series索引对齐直接计算(推荐)
Pandas的Series算术运算会自动按索引对齐,直接计算后转成DataFrame即可,无需手动处理索引:
def standard_pivot(high: pd.Series, low: pd.Series, close: pd.Series) -> pd.DataFrame: """ Returns a `DataFrame` object containing the standard pivot point column. """ pivot_series = (high + low + close) / 3 return pivot_series.to_frame(name='pivot')
方法二:保留assign写法的优化
先将三个Series合并到DataFrame中,再基于DataFrame的列进行计算:
def standard_pivot(high: pd.Series, low: pd.Series, close: pd.Series) -> pd.DataFrame: """ Returns a `DataFrame` object containing the standard pivot point column. """ pivot_df = pd.DataFrame({'high': high, 'low': low, 'close': close}) pivot_df = pivot_df.assign(pivot=lambda x: (x['high'] + x['low'] + x['close'])/3) return pivot_df[['pivot']]
内容的提问来源于stack exchange,提问作者OKprogrammer
相关产品推荐
相关产品推荐

