Ash*_*r11 7 python indexing group-by pandas
我已经对 pandas 执行了 groupby,我想应用一个复杂的函数,该函数需要多个输入,并给出一个 pandas Series 作为输出,我想将其刻录在原始数据框中。这对我来说是一个已知的过程,并且运行得很好 - 除了最后一个案例(我对无法完整发布代码表示歉意)。本质上我得到了一个TypeError: incompatible index of inserted column with frame index. 但是,如下所示,我不应该得到一个。
group_by部分:
all_in_data_risk['weights_of_the_sac'] = all_in_data_risk.groupby(['ptf', 'ac'])['sac', 'unweighted_weights_by_sac', 'instrument_id', 'risk_budgets_sac'].apply(lambda x: wrapper_new_risk_budget(x, temp_fund_all_ret, method_compute_cov))
Run Code Online (Sandbox Code Playgroud)
其中函数是:
def wrapper_new_risk_budget:
print(x.index)
...
print(result.index)
return result.loc[:, 'res']
Run Code Online (Sandbox Code Playgroud)
这引发了这个错误:
raise TypeError('incompatible index of inserted column '
TypeError: incompatible index of inserted column with frame index
Run Code Online (Sandbox Code Playgroud)
问题是这样的:
print(np.array_equal(result.index, x.index))
Run Code Online (Sandbox Code Playgroud)
产生所有True. 这应该是索引匹配的保证,因此问题不应该简单地存在。
现在,我知道我提供的信息至少可以说是很少见的,但是您是否知道问题出在哪里?
ps:我已经尝试将结果转换为数据帧并尝试将输出重新转换为pd.Series(result.loc[:, 'res'].values, index=result.index)
好吧,出于我无法理解的原因,当我在代码中执行合并时,尽管它们的 numpy 表示是等效的,但在 pandas 的眼前它们在其他方面有所不同。我尝试了合并的解决方法(更长且效率更低),现在使用更传统的方式它可以工作。
今天我无法发布完整的示例,因为我的时间非常紧迫,而且截止日期即将到来,但我会尽快完成它,以向那些已经回答或尝试这样做的人表示尊重,并且致所有其他可能发现有助于解决此问题的用户