Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用apply和lambda函数插补缺失值_Python_Pandas_Lambda_Missing Data_Imputation - Fatal编程技术网

Python 使用apply和lambda函数插补缺失值

Python 使用apply和lambda函数插补缺失值,python,pandas,lambda,missing-data,imputation,Python,Pandas,Lambda,Missing Data,Imputation,我试图根据以下代码,根据不同的项目类型取变量的平均值,以此来估算项目权重变量中缺失的值。但当我运行它时,我得到了如下添加的关键错误。是熊猫版不允许这样做还是代码有问题 Item_Weight_Average = train.dropna(subset['Item_Weight']).pivot_table(values='Item_Weight',index='Item_Type') missing = train['Item_Weight'].isnull() train.loc[m

我试图根据以下代码,根据不同的项目类型取变量的平均值,以此来估算项目权重变量中缺失的值。但当我运行它时,我得到了如下添加的关键错误。是熊猫版不允许这样做还是代码有问题

Item_Weight_Average = 
  train.dropna(subset['Item_Weight']).pivot_table(values='Item_Weight',index='Item_Type')

missing = train['Item_Weight'].isnull()

train.loc[missing,'Item_Weight']= train.loc[missing,'Item_Type'].apply(lambda x: Item_Weight_Average[x])

有什么想法或解决办法吗

如果我了解你想做什么,那么有一个更简单的方法来解决你的问题。您可以使用groupby、transform和np.mean按项目类型计算平均项目权重,并使用fillna填充项目权重中缺失的点,而不是生成一系列新的平均值

结果是:

   item_type  item_weight
0          1          2.0
1          1          4.0
2          1          3.0
3          2         10.0
4          2         10.0
5          2         10.0

我使用的是Python3和Pandas版本0.20.3Hi ASGM,这正是我试图做的,您的解决方案非常有效。非常感谢:
# Setting up some toy data
import pandas as pd
import numpy as np
df = pd.DataFrame({'item_type': [1,1,1,2,2,2], 
    'item_weight': [2,4,np.nan,10,np.nan,np.nan]})

# The solution
df.item_weight.fillna(df.groupby('item_type').item_weight.transform(np.mean), inplace=True)
   item_type  item_weight
0          1          2.0
1          1          4.0
2          1          3.0
3          2         10.0
4          2         10.0
5          2         10.0