From 49302974f95f3ebe42e087ef3e98d40435927d21 Mon Sep 17 00:00:00 2001 From: Orpaz Goldstein Date: Fri, 24 Apr 2020 18:06:11 -0700 Subject: [PATCH] support geo codes like 'US--' --- pytrends/request.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/pytrends/request.py b/pytrends/request.py index d7be8903..595fff66 100644 --- a/pytrends/request.py +++ b/pytrends/request.py @@ -279,14 +279,21 @@ def interest_by_region(self, resolution='COUNTRY', inc_low_vol=False, df = pd.DataFrame(req_json['default']['geoMapData']) if (df.empty): return df - + # rename the column with the search keyword - df = df[['geoName', 'geoCode', 'value']].set_index( - ['geoName']).sort_index() + # only if the json has 'geoCode' + has_geo = False + if 'geoCode' in df.columns: + df = df[['geoName', 'geoCode', 'value']].set_index(['geoName']).sort_index() + has_geo = True + # if not, do not use it + else: + df = df[['geoName', 'value']].set_index(['geoName']).sort_index() # split list columns into seperate ones, remove brackets and split on comma result_df = df['value'].apply(lambda x: pd.Series( str(x).replace('[', '').replace(']', '').split(','))) - if inc_geo_code: + # if 'geoCode' exists, add it here + if inc_geo_code and has_geo: result_df['geoCode'] = df['geoCode'] # rename each column with its search term