I've defined a function as below to try to interpolate between two sets of data. When I run it, I get the message:
for i, j in range(0, len(wavelength)):
TypeError: 'int' object is not iterable
I'm not sure what I'm doing wrong. Admittedly, I'm not very good at this.
def accountforfilter(wavelength, flux, filterwavelength, throughput):
filteredwavelength=[]
filteredflux=[]
for i in range(0, len(wavelength)):
if wavelength[i] in filterwavelength[j]:
j=filterwavelength.index(wavelength[i])
filteredwavelength.append(wavelength[i])
filteredflux.append(flux[i]*throughput[j])
elif wavelength[i]<filterwavelength[j]<wavelength[i+1]:
m=((throughput[j+1]-throughput[j])/(filterwavelength[j+1]-filterwavelength[j])
c=throughput[j]-(m*(wavelength[i]))
filteredwavelength.append(wavelength[i])
filteredflux.append(flux[i]*(m*wavelength[i]+c)
return filteredwavelength, filteredflux
range() returns a list of integers. By using for i,j in range() you are telling Python to unpack each item in range() to two values. But since those values are integers, which are a single piece of data, and thus not iterable, you get the error message.
Your code also looks a bit strange.
At first it seems like you want to loop over all combinations of wavelength/filterwavelength, which would be the same as
for i in range(len(wavelength)):
for j in range(len(filterwavelength)):
do_stuff()
but then you are modifying the j parameter inside the loop body, which I don't understand.
Regardless, there is probably a lot easier, and more clear, way to write the code you want. But from the current code it is hard to know what is expected (and should probably go in a separate question).
The problem is that the range only works with one variable like so:
for i in range(0, len(wavelength))
You try to use two variables at once so python tries to unpack an integer which is impossible. You should use the above. If you need two independent indices, use
for i in range(0, len(...))
for j in range(0, len(...))
Btw ranges always start with zero so you can save yourself some typing and use range(len(...)) instead.
You can use zip if you want.
check this: Better way to iterate over two or multiple lists at once
if you have two sets of data.
for i,j in zip(set1,set2):
print i,j
Related
I have a creative problem that I want to solve.
Let's say if I have two list as below. I want to compare if all elements in the req_param list are also in the full_list. I know it is easy to do the same using a for loop and getting the answer. But I am trying to figure out if there is a python3 in-built fxn to do the same..
req_param = ['ele1','ele2','ele3','ele4]
full_param = [['ele1','ele2','ele3','ele4','ele6']
During the comparison, I don't care if there are additional elements in full_param list. I just care that if full_param has all the elements of the req_param, then somehow I want to return it true else, I want to return it false.
Currently, this works with the for loop. But really think there should be an inbuilt fxn like compare. The most important part is that each element may not come in the same order, so I am ok to sort my list before passing it to a fxn...
As was mentioned there are several ways:
Use all(): if all(item in full_list for item in req_param):
Use set(): if set(req_param).issubset(set(full_param)):
I figured out a different way you can solve the problem.
You could just use set() and len() to solve the problem instead of for loop
Here's how:
r = ['ele1','ele2','ele3','ele4']
f = ['ele1','ele2','ele3','ele4','ele6']
print(len(set(r)-set(f))==0)
use all keyword , it returns True if all the conditions are satisfied else it returns False
Please look at this piece of code :
sig_array=[]
...
for i in range (0, 2):
....
temp=[]
for k in range (0, len (sig)):
#print (k)
temp.append(downsample(sig[k],sampl, new_freq))
sig_array.append(temp)
In other words, tempis a list of arrays (my downsamplefunction, as its name may suggest, return an array) and then the temp will be agregated so it would be a list of lists of arrays !
My questions are : How to deal with that (indexing, ...) and is there simplest way to proceed, by generating list of arrays in a loop but how to keep it in a data structure ?
Thanks
Regarding indexing, you'd just refer to elements like sig_array[0], sig_array[1][2] or sig_array[3][0][2] etc.
Regarding any better data structures, it really just depends on your use case. As #smagnan says in the comments, are you using it for easily accessing data? Matrix processing? If so, have a look at numpy ndarrays. You say that you need it for big data on time series analysis. In that case, using the pandas module will be quite helpful (more info).
Also, as #Bazingaa says, you can make your code less verbose by using list comprehensions (more info):
sig_array = [ [downsample(sig[i],sampl, new_freq) for i in range (len(sig))] for _ in range(2)]
With list comprehensions, it's best to start from the outside, and from the end. The for _ in range(2) will run twice (I've replaced your i with _ as I couldn't see you using it anywhere. If you need it, replace _ with a relevant variable name). In each iteration, it'll append the inner list comprehension to the sig_array. Inside the inner listcomp, the result of the downsample() function will be appended to the temporary list for each iteration of the for loop,
This will have exactly the same output as your code, but is clearly way shorter :)
Hi I am trying to create a new array from a previous array. such that in new array the first element is mean of first 20 elements from existing array. Here is my code. I am not sure why its not working.
#Averages
RPMA=[]
for i in range(9580):
for j in range (0,191600):
a=RPM.iloc[j:j+20]
RPMA(i)= a.mean()
Looks to me like you're using the wrong kind of brackets. This line:
RPMA(i)= a.mean()
...should probably be this:
RPMA[i]= a.mean()
But I'm no Python expert. I guessing that it thinks RPMA(i) is a function because you use parentheses, in which case you would be trying to assign a value to a function call, like the error says.
However trying to assign a new value past the end of the array will result in an IndexError because the array element doesn't exist, and will need to be added. What you can do instead is this:
RPMA.append(a.mean())
...which will append the data to the end of the array (i.e. adding a new element).
Thanks everyone. As suggested by most of you, I made below changes in code and now its working just fine!
RPMA=[]
for j in range (0,191600, 20):
a=RPM.iloc[j:j+19]
RPMA.append(a.mean())
I have a function:
def fun(l):
for i in l:
if len(i)==10:
l.append('+91 {} {}'.format(i[:5],i[5:]))
l.remove(i)
if len(i)==11:
j=list(''.join(i))
j.remove(i[0])
l.append('+91 {} {}'.format(''.join(j[:5]),''.join(j[5:])))
l.remove(i)
if len(i)==12:
j=list(''.join(i))
j.remove(i[0])
j.remove(i[1])
l.append('+91 {} {}'.format(''.join(j[:5]),''.join(j[5:])))
l.remove(i)
if len(i)==13:
j=list(''.join(i))
j.remove(i[0])
j.remove(i[1])
j.remove(i[2])
l.append('+91 {} {}'.format(''.join(j[:5]),''.join(j[5:])))
l.remove(i)
return l
say l=['9195969878','07895462130','919875641230']
I am getting the output as
['+91 91959 69878','7895462130','+91 98756 41230']
But i have suppose to get the output as:
['+91 91959 69878','+91 78954 62130,'+91 98756 41230']
Actually this function is escaping all that is positioned even no in 'l' list. Kindly suggest
The first problem is that you're mutating the list while iterating over it. In this particular case, this caused the loop to skip some items, as you deleted items that were earlier. In other Python versions it might trigger an error. But you're returning your result, so I don't see why you're mutating the list at all.
Secondly your code does some roundabout things, in particular ''.join(i) which is absolutely redundant (it literally rebuilds the same string), and series of remove() calls which almost certainly don't do what you expect. If you remove the first item from [1,2,3], the list becomes [2,3], and if you follow that by removing the second item (index 1) you end up with [2]. This is the same sort of issue your for loop has with the other remove.
I would also restructure the code a bit to avoid code duplication. I get something like:
def fun(l):
return ['+91 {} {}'.format(i[-10:-5],i[-5:])
for i in l]
This never alters l, makes one single pass, and joins all the different length behaviours by observing that we're using parts at a fixed distance from the end. There is one caveat: other lengths aren't handled separately. I don't know if those occur, or how you actually want them handled (the old code would leave them as is). We can easily enough specify other behaviour:
def fun(l):
return ['+91 {} {}'.format(i[-10:-5],i[-5:]) if 10<=len(i)<=13
else i
for i in l]
This still doesn't reproduce the behaviour that reformatted numbers were appended at the end, but I'm not sure you really wanted that. It made little sense for the loop to process its own output in the first place.
You are modifying the list l as you go - I would suggest to create a new list and add things to this list. Is there a reason you want to mutate in place?
If you are intent on mutating in place, why not just do something like this?
l[index] = '+91 {} {}'.format(i[:5],i[5:])
Also, here is the first google result for "python phone number library": https://github.com/daviddrysdale/python-phonenumbers as it may be of use to you. (Never used it, am not the maintainer.)
Below are snippets of code that is giving me some problems. what i am trying to do is find every occurrence of a 356 day high. To do this i am trying code similar to the one below, but getting an exception on the "for i" line: 'builtin_function_or_method' object has no attribute 'getitem'
Quote = namedtuple("Quote", "Date Close Volume")
quotes = GetData() # arrray
newHighs = []
for i,q in range[365, len(quotes)]: #<--Exception
max = max(xrange[i-365, i].Close) #<--i know this won't work, will fix when i get here
if (q.Close > max):
newHighs.append(i,q)
Any help on fixing this would be appreciated. Also any tips on implementing this in an efficient manner (since quotes array currently has 17K elements) would also be nice.
range is a function that returns a generator (or list in python2). Thus, it must be called as a function range(365, len(quotes)), which will return all the numbers from 365 to len(quotes).
Square brackets imply indexing, like accessing items in a list. Since range is a function, not a list, it throws an exception when you try to access it.
"Range" is a function. This means you use circle brackets, not square ones. This is the same deal with "xrange" in the line below. I understand why you'd think to use the square brackets, but what "range" does is create the list using those arguments. So it's not the same as when you want elements m to n of a list.