KeyError Traceback (most recent call last) - python

**from geopy.geocoders import Here
exif = get_exif('earth_postcard_1599147372.jpg')
geotags = get_geotagging(exif)
coords = get_coordinates(geotags)
geocoder = Here(apikey=os.environ['API_KEY'])
print(geocoder.reverse("%s,%s" % coords))**
ERROR
KeyError Traceback (most recent call last)
<ipython-input-13-baa26ae24e59> in <module>
4 geotags = get_geotagging(exif)
5 coords = get_coordinates(geotags)
----> 6 geocoder = Here(apikey=os.environ['API_KEY'])
7 print(geocoder.reverse("%s,%s" % coords))
~\anaconda3\lib\os.py in __getitem__(self, key)
677 except KeyError:
678 # raise KeyError with the original key value
--> 679 raise KeyError(key) from None
680 return self.decodevalue(value)
681
KeyError: 'API_KEY'
Here i try to get the location of using latitude and logitude using geopy library but im getting key error

You should check whether you have set your environment parameter.You can enter into python command line mode then input :
import os
os.environ.keys()
System will output all the environment parameter."API_KEY" should not be set. If you set this key in system parameter list,this error will be gone.

Related

KPLR: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I am trying to follow the KPLR tutorial run in Google Colab the last code snippet on the page:
import kplr
client = kplr.API()
# Find the target KOI.
koi = client.koi(952.01)
# Get a list of light curve datasets.
lcs = koi.get_light_curves(short_cadence=False, fetch=True, clobber=True)
# Loop over the datasets and read in the data.
time, flux, ferr, quality = [], [], [], []
for lc in lcs:
with lc.open() as f:
# The lightcurve data are in the first FITS HDU.
hdu_data = f[1].data
time.append(hdu_data["time"])
flux.append(hdu_data["sap_flux"])
ferr.append(hdu_data["sap_flux_err"])
quality.append(hdu_data["sap_quality"])
When I run this though, I receive the following error:
JSONDecodeError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/kplr/api.py in mast_request(self, category, adapter, sort, mission, **params)
197 try:
--> 198 result = json.loads(txt)
199 except ValueError:
7 frames
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
APIError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/kplr/api.py in mast_request(self, category, adapter, sort, mission, **params)
200 full_url = handler.geturl() + "?" + urllib.parse.urlencode(params)
201 raise APIError(code, full_url,
--> 202 "No JSON object could be decoded.\n" + txt)
203
204 # Fake munge the types if no adapter was provided.
Any suggestions?

Python and Pandas KeyError 3 and a refusal to call the function

I am getting KeyError: 3 and a refusal to call the main funciton when trying to use Panda library to import value from excel and use them to send emails according to format importing from an excel file, the code used to work even with KeyError: 3 before I input the file attachment code in. Now the code just refused to work entirely and I even with extensive search I can't pinpoint what is wrong.
The code is a bit messy but please bear with me.
Any help would be appreciate.
from win32com.client import Dispatch
import win32com
import pandas as pd
import win32api
import sys
path = "C:/XXXXX/XXXXX/XXXXX/XXXXX.xlsx"
def mailprepare():
num = range(0, 999)
for k in num:
outlook = win32com.client.Dispatch("Outlook.Application")
for accoun in outlook.Session.Accounts:
if accoun.SmtpAddress == 'XXXXX#XXXXX.com':
newaccount = accoun
break
mail = outlook.CreateItem(0)
mail._oleobj_.Invoke(*(64209, 0, 8, 0, newaccount))
data = pd.ExcelFile(path)
sheet = data.parse('Sheet1')
if (sheet['Send'][k] == 0):
continue
position = sheet['Position'][k]
client = sheet['ClientName'][k]
mailto = sheet['Mails'][k]
company = sheet['Company'][k]
subject = (sheet.iat[0,5])
body = (sheet.iat[0,6])
signature = (sheet.iat[0,7])
mail.To = mailto
mail.Subject = f'{subject}'
mail.Body = f'{company}/n'/
f'{position}/n'/
f'{client}/n'/
f'/n'/
f'{body}/n'/
f'/n'/
f'{signature}'/
if (sheet.iat[0,9]== 1):
filepath = (sheet.iat[0,8])
add_file1 = "C:/XXXXX/XXXXX/XXXXXX/XXXXX.xlsx"
mail.attachments.Add(add_file1)
mail.send
mailprepare()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\range.py:385, in RangeIndex.get_loc(self, key, method, tolerance)
--> 385 return self._range.index(new_key)
ValueError: 3 is not in range
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Input In [1], in <cell line: 49>()
---> 49 mailprepare()
Input In [1], in mailprepare()
---> 23 if (sheet['Send'][k] == 0):
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py:958, in Series.__getitem__(self, key)
--> 958 return self._get_value(key)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py:1069, in Series._get_value(self, label, takeable)
-> 1069 loc = self.index.get_loc(label)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\range.py:387, in RangeIndex.get_loc(self, key, method, tolerance)
--> 387 raise KeyError(key) from err
KeyError: 3

Python load .features file

I have a dataset (Kvasir data set) with several files that contains the features extraction in the format:
JCD:3.0,3.5,6.0...
Tamura:3.608455882352941,6.681779104634786,632.0,130.0...
ColorLayout:11.0,25.0,9.0,4.0,16.0...
EdgeHistogram:0.0,0.0,4.0,0.0,1.0,1.0,4.0...
AutoColorCorrelogram:13.0,13.0,12.0,12.0,13.0,13.0,12.0...
I'm trying to load all the features files with this code:
dat=sklearn.datasets.load_files("/MTU/Q3/kvasir-dataset-v2-features")
df=pd.DataFrame(data=dat.data,columns=dat.feature_names)
but I get this error:
KeyError Traceback (most recent call last)
C:\Python310\lib\site-packages\sklearn\utils\__init__.py in __getattr__(self, key)
116 try:
--> 117 return self[key]
118 except KeyError:
KeyError: 'feature_names'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_22320/2380416560.py in <module>
----> 1 df=pd.DataFrame(data=dat.data,columns=dat.feature_names)
C:\Python310\lib\site-packages\sklearn\utils\__init__.py in __getattr__(self, key)
117 return self[key]
118 except KeyError:
--> 119 raise AttributeError(key)
120
121 def __setstate__(self, state):
AttributeError: feature_names

Error when importing seaborn in Jupyter notebook

When I try to import seaborn I get the following error:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/opt/conda/anaconda/lib/python3.7/site-packages/matplotlib/__init__.py in __setitem__(self, key, val)
800 try:
--> 801 cval = self.validate[key](val)
802 except ValueError as ve:
KeyError: 'axes.color_cycle'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-1-334c7a663000> in <module>
1 import matplotlib.pyplot as plt
----> 2 import seaborn as sns
3 import pandas as pd
4 import nbashots as nba # this will throw a warning if using matplotlib 1.5
5
/opt/conda/anaconda/lib/python3.7/site-packages/seaborn/__init__.py in <module>
11 from .xkcd_rgb import xkcd_rgb
12 from .crayons import crayons
---> 13 set()
14
15 __version__ = "0.6.0"
/opt/conda/anaconda/lib/python3.7/site-packages/seaborn/rcmod.py in set(context, style, palette, font, font_scale, color_codes, rc)
96 set_context(context, font_scale)
97 set_style(style, rc={"font.family": font})
---> 98 set_palette(palette, color_codes=color_codes)
99 if rc is not None:
100 mpl.rcParams.update(rc)
/opt/conda/anaconda/lib/python3.7/site-packages/seaborn/rcmod.py in set_palette(palette, n_colors, desat, color_codes)
489 """
490 colors = palettes.color_palette(palette, n_colors, desat)
--> 491 mpl.rcParams["axes.color_cycle"] = list(colors)
492 mpl.rcParams["patch.facecolor"] = colors[0]
493 if color_codes:
/opt/conda/anaconda/lib/python3.7/site-packages/matplotlib/__init__.py in __setitem__(self, key, val)
805 except KeyError:
806 raise KeyError(
--> 807 f"{key} is not a valid rc parameter (see rcParams.keys() for "
808 f"a list of valid parameters)")
809
KeyError: 'axes.color_cycle is not a valid rc parameter (see rcParams.keys() for a list of valid parameters)'
I'm pretty sure this is because I am using a more recent version of matplotlib and that color_cycle was deprecated in matplotlib 1.5. Any suggestions on how I can fix this issue? I have searched the web for hours but haven't been able to find a solution.

Error when calling Pkg_resources.resource_string

I'm a little confused. I'm working on a Python project where I load a resource file, read it as tsv and transform it into a dictionary with pattern objects as key for later usage. To load the file, so far I've used the pkg_resources package from setuptools. It basically looks like this:
from csv import DictReader
from pkg_resources import resource_string
def make_dict():
"""Make global dictionary."""
global event_dict
dictlines = [l.decode('utf8') for l in resource_string(
'pkgname.resources.tsv', 'event_dict.tsv').splitlines()]
reader = DictReader(dictlines, dialect='excel-tab')
for row in reader:
event = re.compile(r'\b{}\b'.format(re.escape(row['word'])))
classes = string_to_list(row['id'])
event_dict[event] = classes
So far, it worked well. However, once I started calling the module from another module, following error appeared:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
C:\Python\Python36\lib\site-packages\pkg_resources\__init__.py in get_provider(moduleOrReq)
430 try:
--> 431 module = sys.modules[moduleOrReq]
432 except KeyError:
KeyError: 'pkgname.resources.tsv'
During handling of the above exception, another exception occurred:
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-22-efa35954c76f> in <module>()
----> 1 make_event_dict()
<ipython-input-21-b318bc78e8fd> in make_event_dict()
4 global event_dict
5 dictlines = [l.decode('utf8') for l in resource_string(
----> 6 'pkgname.resources.tsv', 'event_classes_dict.tsv').splitlines()]
7 reader = DictReader(dictlines, dialect='excel-tab')
8 for row in reader:
C:\Python\Python36\lib\site-packages\pkg_resources\__init__.py in resource_string(self, package_or_requirement, resource_name)
1215 def resource_string(self, package_or_requirement, resource_name):
1216 """Return specified resource as a string"""
-> 1217 return get_provider(package_or_requirement).get_resource_string(
1218 self, resource_name
1219 )
C:\Python\Python36\lib\site-packages\pkg_resources\__init__.py in get_provider(moduleOrReq)
431 module = sys.modules[moduleOrReq]
432 except KeyError:
--> 433 __import__(moduleOrReq)
434 module = sys.modules[moduleOrReq]
435 loader = getattr(module, '__loader__', None)
ModuleNotFoundError: No module named 'pkgname'
Now I'm guessing something's wrong with my project setup, so this is what it's structured like:
|Pkg\
|----setup.py
|----pkg\
|--------__init__.py
|--------events.py
|--------resources\
|------------__init__.py
|------------tsv\
|----------------__init__.py
|----------------event_dict.tsv
What could be wrong? Not exactly sure if the __init__.py in the subfolders are needed, btw.

Categories