ValueError:无法将float NaN转换为整数

时间:2019-11-26 09:51:27

标签: python-3.x pandas

我正在编写一个函数,该函数返回一个以doc年为键的字典,作为值,它指定由def do_get_citations_per_year函数返回的元组。

此函数处理df:

def do_process_citation_data(f_path):
    global my_ocan

    my_ocan = pd.read_csv(f_path, names=['oci', 'citing', 'cited', 'creation', 'timespan', 'journal_sc', 'author_sc'],
                          parse_dates=['creation', 'timespan'])
    my_ocan = my_ocan.iloc[1:]  # to remove the first row
    my_ocan['creation'] = pd.to_datetime(my_ocan['creation'], format="%Y-%m-%d", yearfirst=True)
    my_ocan['timespan'] = my_ocan['timespan'].map(parse_timespan)
    #print(my_ocan.info())
    print(my_ocan['timespan'])
    return my_ocan

然后我有此功能,在运行它时不会触发任何错误:

    result = tuple()
    my_ocan['creation'] = pd.DatetimeIndex(my_ocan['creation']).year

    len_citations = len(my_ocan.loc[my_ocan["creation"] == year, "creation"])
    timespan = round(my_ocan.loc[my_ocan["creation"] == year, "timespan"].mean())
    result = (len_citations, timespan)
    print(result)


    return result

当我在另一个函数中运行该函数时:

def do_get_citations_all_years(data):
    mydict = {}
    s = set(my_ocan.creation)
    for year in s:
        mydict[year] = do_get_citations_per_year(data, year)

    return mydict

我得到了错误:

  File "/Users/lisa/Desktop/yopy/execution_example.py", line 28, in <module>
    print(my_ocan.get_citations_all_years())
  File "/Users/lisa/Desktop/yopy/ocan.py", line 35, in get_citations_all_years
    return do_get_citations_all_years(self.data)
  File "/Users/lisa/Desktop/yopy/lisa.py", line 112, in do_get_citations_all_years
    mydict[year] = do_get_citations_per_year(data, year)
  File "/Users/lisa/Desktop/yopy/lisa.py", line 99, in do_get_citations_per_year
    timespan = round(my_ocan.loc[my_ocan["creation"] == year, "timespan"].mean())
ValueError: cannot convert float NaN to integer

我该怎么做才能解决此问题?

提前谢谢

2 个答案:

答案 0 :(得分:1)

此错误表示my_ocan.loc[my_ocan["creation"] == year, "timespan"].mean()NaN

在计算均值之前,您应该用NaN填充0值,因为它不会改变均值。这是一个示例:

timespan = my_ocan.loc[my_ocan["creation"] == year, "timespan"].fillna(0).mean()

答案 1 :(得分:0)

@Ha Bom,用零填充将改变平均值,我想解决办法是改为使用NaN删除行:

timespan = my_ocan.loc[my_ocan["creation"] == year, "timespan"].dropna().mean()

例如,如果您不想删除任何行而不是要用均值填充,请参见此Stackoverflow question for an example

编辑 @Ha Bom解决方案很好,因为要点是将均值替换为零