i have this problem in python, python keeps giving me an keyerror: weight
g.add_edge(1,3,weight=2.5)
g[1][2]['weight'] = 1.5
for n1,n2,attr in g.edges(data=True):
print n1,n2,attr['weight']
The output.
KeyError Traceback (most recent call last)
<ipython-input-56-832c29e7e1db> in <module>()
2 g[1][2]['weight'] = 1.5
3 for n1,n2,attr in g.edges(data=True):
----> 4 print n1,n2,attr['weight']
KeyError: 'weight'
0 1
i dont know why weight gives me an error?
My guess is that you have some other edges in your graph, and haven't set the weight attribute for all of them. Try the following:
for n1,n2,attr in g.edges(data=True):
print n1,n2,attr
See if attr contains a value for weight in every case.
Related
I had this problem when trying to solve a optimization problem using pulp.
The code:
import pulp
import numpy as np
import math
prob = pulp.LpProblem("example", pulp.LpMaximize)
# Variable represent number of times device i is used
d = pulp.LpVariable("d", cat=pulp.LpContinuous,lowBound=0,upBound=np.inf)
var = pulp.LpVariable("var", cat=pulp.LpContinuous,lowBound=0,upBound=np.inf)
# The objective function that we want to maximize
n = len(y_arfima)
prob += -(n/2) * np.log(var) - np.sum([np.log((math.gamma(t)*math.gamma(t-2*d))/(math.gamma(t-d)**2)) for t in range(1,n+1)])/2 - 1/2
# Actually solve the problem, this calls GLPK so you need it installed
pulp.GLPK().solve(prob)
# Print out the results
for v in prob.variables():
print (v.name, "=", v.varValue)
The error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
AttributeError: 'LpVariable' object has no attribute 'log'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12336/3027528854.py in <module>
11 # The objective function that we want to maximize
12 n = len(y_arfima)
---> 13 prob += -(n/2) * np.log(var) - np.sum([np.log((math.gamma(t)*math.gamma(t-2*d))/(math.gamma(t-d)**2)) for t in range(1,n+1)])/2 - 1/2
14
15 # Actually solve the problem, this calls GLPK so you need it installed
TypeError: loop of ufunc does not support argument 0 of type LpVariable which has no callable log method
AttributeError Traceback (most recent call last)
AttributeError: 'LpVariable' object has no attribute 'log'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12336/3027528854.py in
11 # The objective function that we want to maximize
12 n = len(y_arfima)
---> 13 prob += -(n/2) * np.log(var) - np.sum([np.log((math.gamma(t)math.gamma(t-2d))/(math.gamma(t-d)**2)) for t in range(1,n+1)])/2 - 1/2
14
15 # Actually solve the problem, this calls GLPK so you need it installed
TypeError: loop of ufunc does not support argument 0 of type LpVariable which has no callable log method
Can you help me?
Thanks!
I have been scratching my head on this for a few days now and cannot seem to find a solution that works online for my problem. I am trying to access data on zendesk and go through the pagination. For some reason, I am getting a KeyError, even though I can see that the key does exist. Here is my code :
data_users2 = [[]]
while url_users:
users_pagination = requests.get(url_users,auth=(user, pwd))
data_user_page = json.loads(users_pagination.text)
print (data_user_page.keys())
for user in data_user_page['users']:
data_users2.append(user)
url = data_user_page['next_page']
Here is the output :
dict_keys(['users', 'next_page', 'previous_page', 'count'])
dict_keys(['error'])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-22-fab95d95ddeb> in <module>
6 data_user_page = json.loads(users_pagination.text)
7 print (data_user_page.keys())
----> 8 for user in data_user_page["users"]:
9 data_users2.append(user)
10 url = data_user_page["next_page"]
KeyError: 'users'
As you can see, users does exist. same thing happens if I try to print the next_page, I get a KeyError for next_page.
Any help would be appreciated ! Thanks!
Your code is failing in its second iteration of the loop, in that moment your keys in data_user_page are just "error" as you can see in the output you have pasted
dict_keys(['users', 'next_page', 'previous_page', 'count']) <----- FIRST ITERATION
dict_keys(['error']) <---- SECOND ITERATION, THEREFORE, YOUR KEY DOES NOT EXISTS
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-22-fab95d95ddeb> in <module>
6 data_user_page = json.loads(users_pagination.text)
7 print (data_user_page.keys())
----> 8 for user in data_user_page["users"]:
9 data_users2.append(user)
10 url = data_user_page["next_page"]
KeyError: 'users'
EDIT: This could be due to the fact that you are saving the next url in a variable called url not url_users
I'm having problems storing the out put of numpy.linalg.eig(). I want to store then into two different array. This is the way I've tried:
vec1 = np.zeros(y.shape[0],dtype=complex)
vec2 = np.zeros(y.shape[0],dtype=complex)
for i in np.arange(y.shape[0]):
val,vec= np.linalg.eig(rho_t[:,:,i])
vec1[i] = vec[0]
vec2[i] = vec[1]
The ERROR message is the following:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-389-791a7e5e4801> in <module>
3 for i in np.arange(y.shape[0]):
4 val,vec= np.linalg.eig(rho_t[:,:,i])
----> 5 vec1[i] = vec[0]
6 vec2[i] = vec[1]
7 #vec2[i] = np.array(sol[1][1])
TypeError: only length-1 arrays can be converted to Python scalars
No idea what is the problem, can somebody help me please
According to documentation: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html
The normalized (unit “length”) eigenvectors, such that the column
v[:,i] is the eigenvector corresponding to the eigenvalue w[i].
so perhaps the solution is this:
for i in np.arange(y.shape[0]):
val,vec= np.linalg.eig(rho_t[:,:,i])
vec1[i] = vec[:,0]
vec2[i] = vec[:,1]
I am trying to slice each sentence in a list of sentences from [0:10] character of it.
Example of list of sentences: list name = sd_list
['I was born and brought up in Delhi.',
'I am using Dell Latitude E5140 laptop since 2012.',
'I work for ABC company since 2014.']
I tried to slice the first 10 characters of each sentence by running the below code and failed.
sent10 = [s[0:10] for s in sd_list]
By running this I encountered below TypeError
TypeError Traceback (most recent call last)
in ()
----> 1 [s[0:10] for s in sd_list]
in (.0)
----> 1 [s[0:10] for s in sd_list]
TypeError: 'float' object is not subscriptable
--> I even tried defining a function :
def sent_slice(text):
for s in range(0,len(text)):
text[s] = text[s][0:10]
return text
sent_slice(sd_list)
TypeError Traceback (most recent call last)
in ()
----> 1 sent_slice(sd_list)
in sent_slice(text)
1 def sent_slice(text):
2 for s in range(0,len(text)):
----> 3 text[s] = text[s][0:10]
4 return text
TypeError: 'float' object is not subscriptable
Could someone help me understand this "TypeError: 'float' object is not subscriptable" . How can I achieve my goal of slicing sentence?
it means that you have a float in sd_list. you can find it by doing something like:
print([f for f in sd_list if isinstance(f, float)])
I have written a code in python to generate a sequence of ARIMA model's and determine their AIC values to compare them.The code is as below,
p=0
q=0
d=0
for p in range(5):
for d in range(1):
for q in range(4):
arima_mod=sm.tsa.ARIMA(df,(p,d,q)).fit()
print(arima_mod.params)
print arima_mod.aic()
I am getting a error message as below,
TypeError Traceback (most recent call last)
<ipython-input-60-b662b0c42796> in <module>()
8 arima_mod=sm.tsa.ARIMA(df,(p,d,q)).fit()
9 print(arima_mod.params)
---> 10 print arima_mod.aic()
global arima_mod.aic = 1262.2449736558815
11
**TypeError: 'numpy.float64' object is not callable**
Remove the brackets after print arima_mod.aic(). As I read it, arima_mod.aic is 1262.2449736558815, and thus a float. The brackets make python think it is a function, and tries to call it. You do not want that (because it breaks), you just want that value. So remove the brackets, and you'll be fine.