2016-07-15 4 views
0

코드를 사용하여 dict을 읽고 일부 변수를 계산하여 마지막에 df에 추가합니다. 나는이 유형의 것을 값을 계산하는 데 사용하고 있습니다.변수가 정의되지 않은 경우 Dataframe에 NaN 추가

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이 나와 있습니다. 그래서 이미 정의 된 경우 그 값을 반환하는 함수를 정의 해 보았습니다. 그 변수를 정의하고 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을 사용하고있다.

답변

0

Numpy NaN은 일반적인 Python과 구별된다. None.

이 시도 :

def ret(x): 
    try: 
     x 
    except NameError: 
     return numpy.nan 
    else: 
     return x 
관련 문제