Attribute Error: list object has no attribute 'apply' - python

time_weight = list(100*np.exp(np.linspace(-1/divisor, -(num_steps-1)/divisor, num_steps))).apply(lambda x:int(x))
When I try this, I get the following error in Python 3.7.
AttributeError: 'list' object has no attribute 'apply'
Can anyone help with this?

As the error said, list type has no apply attribute.
This said, if you have a list l and you want to set to int type every element in it you may use:
l = [int(x) for x in l]
or
l = list(map(int,l))

As the error suggests, list has no apply method. If what you want to do is convert every element to an int, you could remove the lambda function and instead use astype(int):
time_weight = list((100*np.exp(np.linspace(-1/divisor, -(num_steps-1)/divisor, num_steps))).astype(int))

Related

'tuple' object does not support item assignment in torch.cat()

I am trying to use the torch.cat() to contenate the torch tensor. However, I face the error messagge with --> 'tuple' object does not support item assignment.
Here are my code:
inputs = tokenizer.encode_plus(txt, add_special_tokens=False, return_tensors="pt")
input_id_chunks = inputs["input_ids"][0].split(510)
mask_chunks = inputs["attention_mask"][0].split(510)
print(type(input_id_chunks))
for i in range(len(input_id_chunks)):
print(type(input_id_chunks[i]))
print(input_id_chunks[i])
input_id_chunks[i] = torch.cat([
torch.Tensor([101]), input_id_chunks[i], torch.Tensor([102])
])
The outputs looks fine, the inputs_id_chunks[i] is torch.Tensor:
`<class 'tuple'>
<class 'torch.Tensor'>`
But I got the following print and error message:
TypeError: 'tuple' object does not support item assignment
in torch.cat()
I have using the small testing code for torch.cat() and it works fine, but I don't know what is missing in my original codes.
you can't change tuple value, instead you can assign it to list, then append new value to it and then after all changes you want to implement, you should assign again it to tuple.
please check this link

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

I have this piece of code and I am trying to understand it and get the output, but I get the error:
AttributeError: 'int' object has no attribute 'items'
def my_func(A: Set[int], B: List[Dict[int, C]]) -> \
List[Dict[int, C]]:
D = []
for b in B:
E = dict()
for a, m in b.items():
if a in A:
E[a] = m
D.append(E)
return D
A is a set :
A={1,2}
and C is a dictionary:
my_dic = {
1: C(
X=11.0,
Y=34.25,
a=1
),
2: C(
X=51.76,
Y=50.63,
a=2,
)
}
I call the function
X=my_func(A,my_dic)
but it gives me error. I also converted the dictionary to the list and it still gives me error but this time: 'tuple' object has no attribute 'items'. Would you please help me to understand the code better and be able to run it?
You define your func as follows:
def my_func(A: Set[int], B: List[Dict[int, C]])
You say that B will be a list of dict's. But then you call:
X=my_func(A,my_dic)
Where you pass in a single dict instead of the list defined before.
However, later in the func, you refer to .items(), which is a method callable on a dict, but not on a list or an int. When you pass in a single dict instead of a list of dicts, your code is trying to iterate over the element you passed in. Normally you would iterate over the elements of the list. But since you've passed in a dict, it will iterate over the keys of the dict. But your keys are set as int's, so then the .items() call fails.
So you just have to tighten up your call structure.
To quickly comply, you can change:
X=my_func(A,my_dic)
to:
X=my_func(A, [my_dic,])
That should help... At least now you'll be passing in a list of dicts, even if it is just a list of length one.
Because you passed a dictioanry where you were expecting a list (of dictionaries), for b in B: is now looping over the keys of that dictionary. Each key is an int, which you call items on, leading to the error you're seeing.
Try:
X = my_func(A, [my_dic])
Note that Python type signatures in this scenario are not being enforced at runtime. You have specified a list of dictionaries with ints as keys, and C as the value type. Python will not step you from calling: my_func(A, 42) but you will get a runtime error.

Can you use list.index for a list of objects?

If I have a list of objects made from classes, is there a way to get the index of a particular object in that list?
I've tried using list.index like this:
obj_list = [object1(), object2()]
object1_index = obj_list.index(object1())
return object1_index
But this just returns a ValueError, saying that object1() is not in list, even though it is.
object1 is a constructor; each time you say object1() you're constructing a new object of class object1. Hence the object1() in your index() call does not refer to the same object as the one in obj_list.
You could do something like:
next(i for i, x in enumerate(obj_list) if isinstance(x, object1))
to find the index of the first object in obj_list that is an instance of object1.

Calculating the Downside Deviation of an Array of Returns

I'm trying to calculate the downside deviation of an array of returns using the code below:
def downside_deviation(arr):
downside_returns = 0
arr.loc[arr < 0, 'downside_returns'] = arr
down_stdev = downside_returns**2
arraysize = downside_returns.count()
down_stdev = downside_returns.sum()/arraysize
down_stdev = np.sqrt(down_stdev)*np.sqrt(12)
return down_stdev
But I keep encountering the and AttributeError as below:
AttributeError: 'float' object has no attribute 'loc'
I'm wondering if anyone could me on this error as nothing I have tried has worked so far.
Thanks a million for the help in advance!
It seems like the arr variable should a Pandas DataFrame, but you passed the float object for the arr variable. So, it raises the AttributeError: 'float' object has no attribute 'loc'.
Additionally, I see this arr.loc[arr < 0, 'downside_returns'] = arr might raise the next error if your arr is actually a Pandas DataFrame. To use it correctly, you may need to read more in its documentation (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html) - for example, df.loc[df['shield'] > 6, ['max_speed']].
You're passing a float into the function, but it expects it to be a type that has a .loc attribute.
Python is "duck typed". You can pass anything you want as the argument, but when it comes time to use the members, if they are not present you will get an error like this.

Python sort with key=lambda gets TypeError

I am trying to sort a list of objects in Python 3.4 based on the value of the data attribute of each object. If I use
db[count].sort(key=lambda a: a.data)
everything works fine. However, I want the sort to be case insensitive so I use
db[count].sort(key=lambda a: a.data.lower)
but then I get
db[count].sort(key=lambda a: a.data.lower)
TypeError: unorderable types: builtin_function_or_method() < builtin_function_or_method()
Any ideas?
key has to be a callable that returns a value to be sorted. In your case it returns another callable a.data.lower. You need to call lower in order to get the value, so the correct form is:
db[count].sort(key=lambda a: a.data.lower())
You are passing a reference to the lower method instead of calling it.
Try this:
db[count].sort(key=lambda a: a.data.lower())

Categories