我在 pandas 上执行了一个 groupby,我想应用一个复杂的函数,它需要多个输入并给出一个我想在我的原始数据框中刻录的 pandas 系列作为输出。这对我来说是一个已知的程序,并且运行良好 - 在最后一个案例中是 excpet(对于无法完整发布代码,我深表歉意)。基本上我得到一个 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))
函数在哪里:
def wrapper_new_risk_budget:
print(x.index)
...
print(result.index)
return result.loc[:, 'res']
引发此错误的原因:
raise TypeError('incompatible index of inserted column '
TypeError: incompatible index of inserted column with frame index
问题是这样的:
print(np.array_equal(result.index, x.index))
产生所有 True。这应该是索引匹配的保证,因此问题不应该仅仅存在。
现在,我知道我提供的信息至少可以说是稀缺的,但您是否碰巧知道问题出在哪里?
p.s.: 我已经尝试将结果转换为数据帧并尝试将输出重铸为 pd.Series(result.loc[:, 'res'].values, index=result.index)
请您参考如下方法:
我遇到了这个问题,并找到了解决它的方法。 在我的例子中,我需要这样做:df.groupby('id').apply(func),然后它返回一个 nx1 数据帧,它的形状与 df 完全相同.shape[0],但出现同样的问题。
因为第一次groupby时,会得到一个多索引,和df不一样。
但是可以通过reset重新指定origin index来解决问题,比如:
df['a']=df.groupby('id').apply(lambda x:func(x)).reset_index().set_index('level_1').drop('id',axis=1)
顺便说一句,你应该非常小心这个函数。返回数据帧应包含相同的 df 索引。
