Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.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/8/sorting/2.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 使用列中的函数替换列中的NaN时遇到索引越界错误_Python_Pandas_Machine Learning_Data Analysis_Missing Data - Fatal编程技术网

Python 使用列中的函数替换列中的NaN时遇到索引越界错误

Python 使用列中的函数替换列中的NaN时遇到索引越界错误,python,pandas,machine-learning,data-analysis,missing-data,Python,Pandas,Machine Learning,Data Analysis,Missing Data,我试图用下面的函数替换NAN值,但我得到的索引越界错误。这是我的示例数据帧。它有列(日期、中心名称、商品名称、价格、年份)。我正在尝试使用基于相应年份和中心名称列的价格模式()替换缺少值的价格列 例如,对于1997年和Centre_Name='SHIMLA',我正在使用下面的代码替换价格列中缺少的值,并且它正在工作 data.loc[(data['Year']==1997)&(data['Centre_Name']=='SHIMLA')&(data['Price'].isnull

我试图用下面的函数替换NAN值,但我得到的索引越界错误。这是我的示例数据帧。它有列(日期、中心名称、商品名称、价格、年份)。我正在尝试使用基于相应年份和中心名称列的价格模式()替换缺少值的价格列

例如,对于1997年和Centre_Name='SHIMLA',我正在使用下面的代码替换价格列中缺少的值,并且它正在工作

data.loc[(data['Year']==1997)&(data['Centre_Name']=='SHIMLA')&(data['Price'].isnull()),'Price']=data.loc[(data['Year']==1997)&(data['Centre_Name']=='SHIMLA'),'Price'].mode()[0]
但下面的函数不起作用。请帮助

year_list=list(data['Year'].unique())
for each_year in year_list:
    city_list=list(data[data['Year']==each_year]['Centre_Name'].unique())
    for each_city in city_list:
        data.loc[(data['Year']==each_year)&(data['Centre_Name']==each_city)&(data['Price'].isnull()),'Price']=data.loc[(data['Year']==each_year)&(data['Centre_Name']==each_city),'Price'].mode()[0]

在第二个脚本中,将
data.iloc
替换为
data.loc
在第二个脚本中,将
data.iloc
替换为
data.loc

谢谢您的建议。我已将data.iloc替换为data.loc,但我还是发现索引越界了,你的代码基本上会尝试每年和每个城市的每一个组合,对吗?但这些组合真的存在吗?如果其中任何一个丢失,您将得到找不到的错误,这可能会导致索引越界。我想如果你能在问题中添加示例数据内容会很有帮助的谢谢你的建议。我已经用data.loc替换了data.iloc,但是我仍然得到了索引超出范围的错误。你的代码基本上会尝试年份和城市的每一个组合,对吗?但这些组合真的存在吗?如果其中任何一个丢失,您将得到找不到的错误,这可能会导致索引越界。我认为如果你能在你的问题中加入样本数据内容,那会很有帮助