Pynmea2 attribute error - python-2.7

I've been using the pynmea2 library, but today I ran a GPGGA message through it and it's throwing an attribute error when trying to access the objects datetime method.
>>> from pynmea2 import parse
>>> a = '$GPGGA,201326.000,3348.5072,N,11809.6409,W,2,20,0.55,37.5,M,-34.3,M,0000,0000*65'
>>> msg = parse(a)
>>> msg
<GGA(timestamp=datetime.time(20, 13, 26), lat='3348.5072', lat_dir='N', lon='11809.6409', lon_dir='W', gps_qual='2', num_sats='20', horizontal_dil='0.55', altitude=37.5, altitude_units='M', geo_sep='-34.3', geo_sep_units='M', age_gps_data='0000', ref_station_id='0000')>
>>> msg.datetime
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/pynmea2/nmea.py", line 154, in __getattr__
raise AttributeError(name)
AttributeError: datetime
Here's what line 154 and everything related states in nmea.py:
def __getattr__(self, name):
#pylint: disable=invalid-name
t = type(self)
try:
i = t.name_to_idx[name]
except KeyError:
raise AttributeError(name)
f = t.fields[i]
if i < len(self.data):
v = self.data[i]
else:
v = ''
if len(f) >= 3:
if v == '':
return None
return f[2](v)
else:
return v
Any ideas what this could be?
Thanks for looking at this!

Found it...GPGGA sentences have no date values in their string.

I think you want to access the timestamp attribute of the GPGGA record, using:
>>> from pynmea2 import parse
>>> a = '$GPGGA,201326.000,3348.5072,N,11809.6409,W,2,20,0.55,37.5,M,-34.3,M,0000,0000*65'
>>> msg = parse(a)
>>> msg
<GGA(timestamp=datetime.time(20, 13, 26), lat='3348.5072', lat_dir='N', lon='11809.6409', lon_dir='W', gps_qual='2', num_sats='20', horizontal_dil='0.55', altitude=37.5, altitude_units='M', geo_sep='-34.3', geo_sep_units='M', age_gps_data='0000', ref_station_id='0000')>
>>> msg.timestamp
datetime.time(20, 13, 26)

Related

Appending list but got "AttributeError: 'NoneType' object has no attribute 'append'" Python 2.7

I keep having this error on my code, which says:
"AttributeError: 'NoneType' object has no attribute 'append'"
But there is interesting fact, it only occurs when "n" is odd.
Here is the piece of code I'm using:
Note: I'm using Python 2.7.18
def sol(n, df):
if n == 1:
result = df
elif n == 2 or n == 0:
df.append(1)
result = df
elif n % 2 == 0:
df.append(n/2)
df = sol(n/2, df)
else:
df_2 = df[:]
df_2 = df_2.append(n-1)
n_2 = n-1
df_2 = sol(n_2, df_2)
return df
df = []
n = input('n == ')
sol(n, df)
The error is as follow:
n == 3
Traceback (most recent call last):
File "Challenge_3_1_vTest.py", line 27, in <module>
solution(n)
File "Challenge_3_1_vTest.py", line 6, in solution
print((sol(n, df)))
File "Challenge_3_1_vTest.py", line 21, in sol
df_2 = sol(n_2, df_2)
File "Challenge_3_1_vTest.py", line 12, in sol
df.append(1)
AttributeError: 'NoneType' object has no attribute 'append'
The append function doesn't return a thing, that's why I was having the error and was passing a none when using number that are not power of 2.
df_2 = df_2.append(n-1)
This line of code was the source of the problem, I should have done:
df_2.append(n-1)

Magic method __repr__ leads to AttributeError with __new__ method

My goal is to give numpy.ndarray a different representation, since I want to represent some arrays with units. Thus, I programmed a class that inherits its attributes/ methods from numpy.ndarray. For the another representation I wanted to use the __repr__ magic method like:
class Quantitiy(np.ndarray):
def __new__(cls, value, unit=None, dtype=None, copy=True, order=None, subok=False, ndmin=0):
value = np.asarray(value)
obj = np.array(value, dtype=dtype, copy=copy, order=order,
subok=True, ndmin=ndmin).view(cls)
obj.__unit = util.def_unit(unit)
obj.__value = value
return obj
def __repr__(self):
prefix = '<{0} '.format(self.__class__.__name__)
sep = ','
arrstr = np.array2string(self.view(np.ndarray),
separator=sep,
prefix=prefix)
return '{0}{1} {2}>'.format(prefix, arrstr, self.__unit)
So far this works fine. However, if I want to access the inherited methods from numpy.ndarray I get a AttributeError because __repr__ cant resolve self.__unit.
I tried to solve this problem with a private method that defines the variable self.__unit and called it within the __new__ method but without success:
class Quantitiy(np.ndarray):
def __new__(cls, value, unit=None, dtype=None, copy=True, order=None, subok=False, ndmin=0):
value = np.asarray(value)
obj = np.array(value, dtype=dtype, copy=copy, order=order, subok=True, ndmin=ndmin).view(cls)
# Here I call the private method to initialize self.__unit.
obj.__set_unit()
obj.__value = value
return obj
def __repr__(self):
prefix = '<{0} '.format(self.__class__.__name__)
sep = ','
arrstr = np.array2string(self.view(np.ndarray), separator=sep, prefix=prefix)
return '{0}{1} {2}>'.format(prefix, arrstr, self.__unit)
# New defined private class.
def __set_unit(self, unit):
self.__unit = util.def_unit(unit)
I can not solve this with something like cls.__unit = util.def_unit(unit) in the __new__ method. I already tried to define a __init__ method after __new__. Moreover, I tried to interchange the private methods with public methods.
What I expect:
>>> array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> q = Quantity(value, unit="meter / second")
>>> q
<Quantitiy [[1,2,3,4],
[5,6,7,8]] meter/second>
>>> q * q
>>> <Quantitiy [[ 1, 4, 9,16],
[25,36,49,64]] meter**2/second**2>
>>> q.min()
>>> <Quantitiy 1 meter/second>
The actual result is:
>>> array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> q = Quantity(value, unit="meter / second")
>>> q
<Quantitiy [[1,2,3,4],
[5,6,7,8]] meter/second>
>>> q * q
>>> <Quantitiy [[ 1, 4, 9,16],
[25,36,49,64]] meter**2/second**2>
# Up to here everything works fine.
>>> q.min()
>>> AttributeError: 'Quantitiy' object has no attribute
'_Quantitiy__unit'
Does anyone see the mistake and can help me?
Ok, the answer is - as usual - in the FineManual (and could be found searching for "subclassing numpy ndarray" - which is how I found it actually), and requires implementing __array_finalize__(self, obj) :
import numpy as np
class Quantitiy(np.ndarray):
def __new__(cls, value, unit=None, dtype=None, copy=True, order=None, subok=False, ndmin=0):
value = np.asarray(value)
x = np.array(value, dtype=dtype, copy=copy, order=order, subok=True, ndmin=ndmin)
obj = x.view(type=cls)
obj._unit = unit
obj._value = value
return obj
def __repr__(self):
print("repr %s" % type(self))
prefix = '<{0} '.format(self.__class__.__name__)
sep = ','
arrstr = np.array2string(self.view(np.ndarray),
separator=sep,
prefix=prefix)
return '{0}{1} {2}>'.format(prefix, arrstr, self._unit)
def __array_finalize__(self, obj):
# see InfoArray.__array_finalize__ for comments
if obj is None:
return
self._unit = getattr(obj, '_unit', None)
self._value = getattr(obj, '_value', None)

Invalid literal for float in k nearest neighbor

I am having the hardest time figuring out why i am getting this error. I have searched a lot but unable to fine any solution
import numpy as np
import warnings
from collections import Counter
import pandas as pd
def k_nearest_neighbors(data, predict, k=3):
if len(data) >= k:
warnings.warn('K is set to a value less than total voting groups!')
distances = []
for group in data:
for features in data[group]:
euclidean_distance = np.linalg.norm(np.array(features)-
np.array(predict))
distances.append([euclidean_distance,group])
votes = [i[1] for i in sorted(distances)[:k]]
vote_result = Counter(votes).most_common(1)[0][0]
return vote_result
df = pd.read_csv("data.txt")
df.replace('?',-99999, inplace=True)
df.drop(['id'], 1, inplace=True)
full_data = df.astype(float).values.tolist()
print(full_data)
After running. it gives error
Traceback (most recent call last):
File "E:\Jazab\Machine Learning\Lec18(Testing K Neatest Nerighbors
Classifier)\Lec18(Testing K Neatest Nerighbors
Classifier)\Lec18_Testing_K_Neatest_Nerighbors_Classifier_.py", line 25, in
<module>
full_data = df.astype(float).values.tolist()
File "C:\Python27\lib\site-packages\pandas\util\_decorators.py", line 91, in
wrapper
return func(*args, **kwargs)
File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 3299, in
astype
**kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3224, in
astype
return self.apply('astype', dtype=dtype, **kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3091, in
apply
applied = getattr(b, f)(**kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 471, in
astype
**kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 521, in
_astype
values = astype_nansafe(values.ravel(), dtype, copy=True)
File "C:\Python27\lib\site-packages\pandas\core\dtypes\cast.py", line 636,
in astype_nansafe
return arr.astype(dtype)
ValueError: invalid literal for float(): 3) <-----Reappears in Group 8 as:
Press any key to continue . . .
if i remove astype(float) program run fine
What should i need to do ?
There are bad data (3)), so need to_numeric with apply because need processes all columns.
Non numeric are converted to NaNs, which are replaced by fillna to some scalar, e.g. 0:
full_data = df.apply(pd.to_numeric, errors='coerce').fillna(0).values.tolist()
Sample:
df = pd.DataFrame({'A':[1,2,7], 'B':['3)',4,5]})
print (df)
A B
0 1 3)
1 2 4
2 7 5
full_data = df.apply(pd.to_numeric, errors='coerce').fillna(0).values.tolist()
print (full_data)
[[1.0, 0.0], [2.0, 4.0], [7.0, 5.0]]
It looks like you have 3) as an entry in your CSV file, and Pandas is complaining because it can't cast it to a float because of the ).

adding item in the dictionary coming from a list resulted in TypeError

this is the code:
import bisect
data = {'sal': 25000} # stored data from user input
table = {1249.99: 36.30, 1749.99: 54.50, 2249.99: 72.70, 2749.99: 90.80,
3249.99: 109.00, 3749.99: 127.20, 4249.99: 145.30, 4749.99: 163.50,
5249.99: 181.70, 5749.99: 199.80, 6249.99: 218.00, 6749.99: 236.20,
7249.99: 254.30, 7749.99: 272.50, 8249.99: 290.70, 8749.99: 308.80,
9249.99: 327.00, 9749.99: 345.20, 10249.99: 363.30, 10749.99: 381.50,
11249.99: 399.70, 11749.99: 417.80, 12249.99: 436.00, 12749.99:
454.20, 13249.99: 472.30, 13749.99: 490.50, 14249.99: 508.70,
14749.99: 526.80, 15249.99: 545.00, 15749.99: 563.20, 15750.00:
581.30}
# get corresponding value from the table
table_bisect = bisect.bisect(sorted(table), data['sal'])
if table_bisect >= 30:
table_bisect = 30
else:
table_bisect = table_bisect
s_table = sorted(table.value())
data['new'] = ''.join(s_table[table_bisect:(table_bisect+1)]
# TypeError: sequence item 0: expected string, float found
Everything works fine, until the last line, which return the error above. How can I fix the error or what are the work around?
It is because if you slice with list[index:index+1], it simply returns one value, which in this case is a float:
>>> y = [21, 4, 2, 5, 4, 3, 7, 9]
>>> y[5:6]
[3]
>>> ''.join(y[5:6])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>>
Instead, just do the following:
data['new'] = s_table[table_bisect:(table_bisect+1)][0]
Another option is to do this:
data['new'] = ''.join(str(s_table[table_bisect:(table_bisect+1)]))
the join() method expects string type if you need to use it.

AttributeError: 'tuple' object has no attribute 'items'

import re, time, _thread
import urllib.request
from bs4 import BeautifulSoup
def get_data(n):
global s,r
html=urllib.request.urlopen('http://www.fmkorea.com/index.php?mid=best&listStyle=webzine&page='+str(n))
soup=BeautifulSoup(html,'lxml')
l=soup.findAll('h3', {'class':'title'})
for i in l:
for j in re.split(r'''\)|\(|\'|\"|\?|\]|\[|,|\.|\ |\:''',i.text[:i.text.rfind('[')].strip()):
s[j.strip()] = s.get(j.strip(),0) + 1
r=r+1
s={}
r=0
for _ in range(1,2037):
_thread.start_new_thread(get_data, (_,))
time.sleep(0.05)
while r!=2036:
time.sleep(3)
with open('res','w') as f:
s=sorted(s.items(),key=lambda x: x[1],reverse=True)
for i in s:
f.writelines(str(i[0]) + " : " + str(i[1])+"\n")
AttributeError Traceback (most recent call last)
<ipython-input-24-3e6cc449e797> in <module>()
35 #
36 with open('res','w') as f:
---> 37 s=sorted(s.items(),key=lambda x: x[1],reverse=True)
38 for i in s:
39 f.writelines(str(i[0]) + " : " + str(i[1])+"\n")
AttributeError: 'list' object has no attribute 'items'
I keep getting this error for the code above and cannot seem to fix it. How do I prevent the AttributeError from being raised?
items is for dictionaries you cant use it on list
>>> d = {1:'a'}
>>> d.items()
dict_items([(1, 'a')])
>>> l = [1,2]
>>> l.items()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'items'