我想用在对Item_Fat_Content和Item_weight列进行分组时获得的相应平均权重来填充Item_Weight列中的空值。
DataFrame:
GroupBy代码:
x=data.groupby(by=['Item_Fat_Content']).mean()[['Item_Weight']]
x
GroupBy输出:
我已经尝试过以下for循环从表中提取平均值:
def impute_weight(cols):
Item_Fat_Content=cols[0]
Item_Weight=cols[1]
if pd.isnull(Item_Weight):
if Item_Fat_Content=='LF':
return x.loc['LF']
if Item_Fat_Content=='Low Fat':
return y
if Item_Fat_Content=='Regular':
return x.loc['Regular']
if Item_Fat_Content=='low fat':
return z
if Item_Fat_Content=='reg':
return x.loc['reg']
执行上述循环后,我尝试将这些值插入到我的原始数据帧中。
data['Item_Weight']=data[['Item_Weight','Item_Fat_Content']].apply(impute_weight,axis=1)
请帮助我解决问题。