我在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))
其中函数为:
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
。这应该是索引匹配的保证,因此问题不应该简单地存在。
现在,我知道我提供的信息很少,至少可以说,但您是否恰好了解问题所在?
附言:我已经尝试在数据帧中转换结果,并尝试将输出重新转换为pd.Series(result.loc[:, 'res'].values, index=result.index)
发布于 2016-09-08 15:59:13
好吧,出于我无法理解的原因,当我在代码中执行合并时,尽管它们的numpy表示是等价的,但它们在熊猫眼前的其他方面有所不同。我尝试了一种合并的变通方法(时间更长,效率更低),现在使用更传统的方法它可以工作。
今天我不能发布完整的示例,因为我的时间非常紧迫,而且我的最后期限迫在眉睫,但我会尽快完成它,以表示对那些已经回答或尝试这样做的人以及所有其他用户的尊重,这些用户可能会在解决这个问题时发现一些有益的东西
发布于 2021-03-19 21:26:38
我遇到了这个问题,并找到了解决它的方法。在我的例子中,我需要这样做:df.groupby('id').apply(func)
,然后它返回一个nx1数据帧,它的形状与df.shape[0]
完全相同,但它发生了同样的问题。
这是因为当你第一次使用groupby时,你会收到一个多重索引,这与df不同。
但您可以通过重置并重新指定原始索引来解决此问题,例如:
df['a']=df.groupby('id').apply(lambda x:func(x)).reset_index().set_index('level_1').drop('id',axis=1)
顺便说一句,你应该非常小心这个函数。返回的dataframe应该包含相同的df索引。
发布于 2021-07-21 18:51:05
简化了问题:
在最初的问题中,应该这样做:
df[‘new_column’] = df.groupby(...).aggregationfunction()
如果至少满足以下条件中的一个,则通常可以执行此操作:
如果这两个条件没有同时给出,则可能会出现错误“TypeError: incompatible index of the inserted column with frame index”。
上升误差的示例
请参见以下示例:
df = pd.DataFrame({'foo':[0,1]*2,'foo2':np.zeros(4).astype(int),'bar':np.arange(4)})
df
> foo foo2 bar
> 0 0 0 0
> 1 1 0 1
> 2 0 0 2
> 3 1 0 3
df['bar_max'] = df.groupby(['foo','foo2'])['bar'].max()
> TypeError: incompatible index of inserted column with frame index
解决方案
使用groupby中的"as_index= False“,您可以创建一个数据帧,该数据帧可以连接到原始数据帧:
df_grouped = df.groupby(['foo','foo2'], as_index= False)['bar'].max().rename(columns={'bar': 'bar_max'})
df = df.merge(df_grouped, on = ['foo','foo2'])
df
> foo foo2 bar bar_max
>0 0 0 0 2
>1 0 0 2 2
>2 1 0 1 3
>3 1 0 3 3
https://stackoverflow.com/questions/39384749
复制相似问题