如果未定义变量,则将NaN附加到Dataframe

时间:2016-07-15 10:47:23

标签: python dataframe

我正在使用代码来读取字典,然后计算一些变量并将其附加到df中。我正在使用这种类型的东西来计算价值。

try:
    most_visited_city = sorted_cities[-1]
    per_visit_max_city = 100 * cities[sorted_cities[-1]]['count'] / float(total_visits)
    if total_visits > 1:        
        avg_visit_gap_max_city = cities[sorted_cities[-1]]['sum of visit gap']/float(total_visits-1)


    secod_max_visited_city = sorted_cities[-2]
    per_visit_2ndmax_city = 100 * cities[sorted_cities[-2]]['count'] / float(total_visits)
    if total_visits > 1:        
        avg_visit_gap_2ndmax_city = cities[sorted_cities[-2]]['sum of visit gap']/float(total_visits-1)


    third_max_visited_city = sorted_cities[-3]
    per_visit_3rdmax_city = 100 * cities[sorted_cities[-3]]['count'] / float(total_visits)
    if total_visits > 1:        
        avg_visit_gap_3rdmax_city = cities[sorted_cities[-3]]['sum of visit gap']/float(total_visits-1)


except IndexError:
    pass

然后像这样追加。

df = df.append({'mac_address': mac, 'Last Seen' : last_seen ,'total no. of visits': total_visits, 'Percentage visit to max visited City': per_visit_max_city, 'Percentage visit to second max visited City': per_visit_2ndmax_city, 'Percentage visit to third max visited City': per_visit_3rdmax_city, ignore_index=True)

所以它给了我NameError: name 'per_visit_2ndmax_city' is not defined一些显而易见的行。所以我尝试定义一个函数来返回它的值,如果已经定义了else,那么定义该变量并返回Nan。我尝试通过一个函数来做到这一点。

def ret(x):
    try:
        x
    except NameError:
        return None 
    else:
        return x

然后这样做

df = df.append({'mac_address': mac, 'Last Seen' : last_seen ,'total no. of visits': total_visits, 'Percentage visit to max visited City': ret(per_visit_max_city), 'Percentage visit to second max visited City': ret(per_visit_2ndmax_city), 'Percentage visit to third max visited City': ret(per_visit_3rdmax_city), ignore_index=True)

没有工作对此有任何帮助。我正在使用Python2.7

1 个答案:

答案 0 :(得分:0)

Numpy NaN与通用Python无区别。

试试这个:

def ret(x):
    try:
        x
    except NameError:
        return numpy.nan
    else:
        return x