AttributeError: 'tuple' object has no attribute Latitude - apache-spark

Can someone please explain to me, why when I write like this everything works fine:
def create_geo_hash(lat, lon):
latitude = float(lat)
longitude = float(lon)
geo_hash = pygeohash.encode(latitude, longitude, precision=4)
return geo_hash
def fill_with_valid_coords(df: DataFrame) -> DataFrame:
validated_rdd = df.rdd.map(lambda row: check_for_invalid_coords(row))
geo_hash_rdd = validated_rdd.map(lambda row: (create_geo_hash(row[5], row[6]), ))
geo_hash_df = geo_hash_rdd.toDF(schema=['Geo_Hash'])
return geo_hash_df
But when I pass the entire row to the mapping function like this:
geo_hash_rdd = validated_rdd.map(lambda row: create_geo_hash(row))
and change my create_geo_hash function accordingly:
def create_geo_hash(row):
latitude = float(row.Latitude)
longitude = float(row.Longitude)
geo_hash = pygeohash.encode(latitude, longitude, precision=4)
return geo_hash
I am having AttributeError: 'tuple' object has no attribute 'Latitude'
When I pass entire row to the validated_rdd = df.rdd.map(lambda row: check_for_invalid_coords(row)) and then use it in another function as a row it works fine.

Related

Tkinter search query in database: TypeError: 'NoneType' object is not iterable

I'm unable to solve a problem with a search query in the database (sqlite3) in Tkinter. Parts of my code:
front.py
# Entries
self.name_text = tk.StringVar()
self.entry_name = tk.Entry(self.parent, textvariable=self.name_text)
self.entry_name.grid(row=3, column=1)
self.color_text = tk.StringVar()
self.combobox2=ttk.Combobox(self.parent, textvariable=self.color_text)
self.combobox2["values"] = ('red','blue','white')
self.labelCombobox=ttk.Label(self.parent, textvariable=self.color_text)
self.combobox2.grid(row=4, column=1)
self.parent.bind('<Return>',lambda e:refresh())
def search_command(self):
self.listBox.delete(0,tk.END)
for row in backend.database.search(self.name_text.get(),self.color_text.get()):
self.listBox.insert(tk.END, row)
backend.py class database:
def search(name="",color=""):
try:
connect = sqlite3.connect("color.db")
cur = connect.cursor()
sql = "SELECT * FROM color WHERE name=? OR color=?"
values = (self, name_text.get(), color_text.get())
cur.execute(sql, values)
rows = cur.fetchall()
name_text.set(rows[1])
color_text.set(rows[2])
entry_name.configure('disabled')
combobox2.configure('disabled')
connect.close()
except:
messagebox.showinfo('nothing found!')
I also tried to put a self in in an other version of backend.py. This gives the same error.
def search(self, name="",color=""):
try:
self.connect = sqlite3.connect("color.db")
self.cur = self.connect.cursor()
self.sql = "SELECT * FROM color WHERE name=? OR color=?"
self.values = (self, name_text.get(), color_text.get())
self.cur.execute(sql, values)
self.rows = self.cur.fetchall()
self.name_text.set(rows[1])
self.color_text.set(rows[2])
self.entry_name.configure('disabled')
self.combobox2.configure('disabled')
self.connect.close()
except:
messagebox.showinfo('nothing!')
Please help solve the error:
for row in backend.database.search(self.name_text.get(),self.color_text.get()):
TypeError: 'NoneType' object is not iterable
There are few issues on the backend.database.search() function:
name_text and color_text are undefined
passed arguments name and color should be used in values instead
it does not return any result (this is the cause of the error)
Below is a modified search() function:
def search(name="", color=""):
rows = () # assume no result in case of exception
try:
connect = sqlite3.connect("color.db")
cur = connect.cursor()
sql = "SELECT * FROM color WHERE name=? OR color=?"
values = (name, color) # use arguments name and color instead
cur.execute(sql, values)
rows = cur.fetchall()
connect.close()
except Exception as e:
print(e) # better to see what is wrong
messagebox.showinfo('nothing found!')
return rows # return result
The error TypeError: 'NoneType' object is not iterable means that your query is returning no rows.
That is at least partly because of this code:
sql = "SELECT * FROM color WHERE name=? OR color=?"
values = (self, name_text.get(), color_text.get())
cur.execute(sql, values)
This caused self to be used for the name parameter, and the result of name_text.get() will be associated with the color attribute. The result of color_text.get() is ignored.
You need to remove self - your sql uses two parameters so you need to send it two parameters.
The other problem appears to be that you're iterating over the results of search, but search doesn't return anything. You need to add a return statement to the search function.

Writing to a dataframe through a loop

I have a dataframe with two columns, one called 'name' that is a string, and one called 'route' that is a Google polyline. I'm using the polyline library to decode the polyline into lat/long. I want to loop over each row to decode but it only seems to decode only the first row and write it to the rest of the created column. This is what I have so far.
df = pd.DataFrame(activities)
for row in df.itertuples(index=False):
name = row[0]
route = row[1]
try:
decoded = polyline.decode(route.replace('\\\\','\\'), geojson=True)
df['decode'] = df.apply(lambda route: [decoded], axis=1)
except:
print(name)
Use DataFrame.apply with function:
df = pd.DataFrame(activities)
def decoder(name, route):
try:
return polyline.decode(route.replace('\\\\','\\'), geojson=True)
except:
print (name)
return np.nan
df['decode'] = df.apply(lambda x: decoder(x[0], x[1]), axis=1)

'list' object is not callable: TypeError

I have a function which is returning 2 values. When I try to fetch those values in a list in another function, it is giving the following error:
'list' object is not callable: TypeError
Here is the function returning two values.
def function():
return val1, val2
Here is the other function calling function():
def function1():
values = []
values = function()
value_1 = values[0]
value_2 = values[1]
function() returns two values, which cannot be stored in a single variable 'values', so instead make function() return a list of those two values
def function():
return [val1,val2]
def function1():
values=function()
value_1=values[0]
value_2=values[1]
You don't need values=[] since it will get overridden anyways by values=function()
Your code should not throw that exception, as the return from function is a tuple.
However here is a modified version of your code which returns a list.
def function():
val1 = 10
val2 = 20
#return the values in a list
return [val1, val2]
def function1():
values = function()
value_1 = values[0]
value_2 = values[1]
print(value_1, value_2)
function1()
Output:
10 20
Here you go
def function():
#return any predefined value here
return 1, 2
def function1():
values = []
a,b = function()
values.append(a)
values.append(b)
print(values)
function1()
Output:
[1, 2]

AttributeError: 'Series' object has no attribute 'iterrows'

accounts = pd.read_csv('C:/*******/New_export.txt', sep=",", dtype={'number': object})
accounts.columns = ["Number", "F"]
for i, j in accounts["Number"].iterrows(): #i represents the row(index number), j is the number
if (str(j) == "27*******5"):
print(accounts["F"][i], accounts["Number"][i])
I get the following error:
AttributeError: 'Series' object has no attribute 'iterrows'
I don't quite understand the error since "accounts" is a pandas dataframe. Please assist.
accounts["Number"] is a Series object, not a DataFrame. Either iterate over accounts.iterrows() and take the Number column from each row, or use the Series.iteritems() method.
Iterating over the dataframe:
for i, row in accounts.iterrows():
if str(row['Number']) == "27*******5":
print(row["F"], row["Number"])
or over Series.iteritems():
for i, number in accounts['Number'].iteritems():
if str(number) == "27*******5":
print(accounts["F"][i], number)

get specific value from list object - python

I have a data like
sql = "select value, type from table"
cur.execute(sql)
row_headers = [x[0] for x in cur.description] #this will extract row headers
rv = cur.fetchall()
json_result = []
for result in rv:
json_result.append(dict(zip(row_headers, result)))
finalresult = json.dumps(json_result)
#[{'value':30,'type':'SS'},{'value':40,'type':'KK'},{'value':80,'type':'SK'}]
attrList = list(map(lambda x: x['value'], finalresult))
return attrList
I want OP :
[30,40,80]
But I am getting ERROR :
attrList = list(map(lambda x: x['value'], finalresult))
TypeError: string indices must be integers
Where am I doing mistake?

Resources