【问题标题】:Facing Index out of bounds Error when replacing NaNs in a column using a function in Pandas使用 Pandas 中的函数替换列中的 NaN 时面临索引越界错误
【发布时间】:2020-10-19 14:40:53
【问题描述】:

我正在尝试使用以下函数替换 NAN 值,但出现索引超出范围错误。This 是我的示例数据框。它有列(日期、中心名称、商品名称、价格、年份)。我正在尝试使用基于相应年份和中心名称列的价格的 MODE() 替换价格列缺失值。

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

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]

【问题讨论】:

    标签: python pandas machine-learning data-analysis missing-data


    【解决方案1】:

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

    【讨论】:

    • 感谢您的建议。我已将 data.iloc 替换为 data.loc ,但仍然出现 Index out of Bound 错误
    • 您的代码基本上会尝试年份和城市的每一种组合,对吧?但是所有这些组合真的存在吗?如果缺少其中任何一个,您将收到无法找到的错误,这可能导致索引超出范围。我认为如果您将示例数据内容也添加到您的问题中会很有帮助
    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2014-06-06
    • 2015-03-22
    • 2018-06-29
    相关资源
    最近更新 更多