thats what I get:
TypeError: 'float' object is unsubscriptable
Thats what I did:
import numpy as N
import itertools
#I created two lists, containing large amounts of numbers, i.e. 3.465
lx = [3.625, 4.625, ...]
ly = [41.435, 42.435, ...] #The lists are not the same size!
xy = list(itertools.product(lx,ly)) #create a nice "table" of my lists
#that iterttools gives me something like
print xy
[(3.625, 41.435), (3.625, 42.435), (... , ..), ... ]
print xy[0][0]
print xy[0][1] #that works just fine, I can access the varios values of the tuple in the list
#down here is where the error occurs
#I basically try to access certain points in "lon"/"lat" with values from xy through `b` and `v`with that iteration. lon/lat are read earlier in the script
b = -1
v = 1
for l in xy:
b += 1
idx = N.where(lon==l[b][b])[0][0]
idy = N.where(lat==l[b][v])[0][0]
lan/lot are read earlier in the script. I am working with a netCDF file and this is the latitude/longitude,read into lan/lot.
Its an array, build with numpy.
Where is the mistake?
I tried to convert b and v with int() to integers, but that did not help.
The N.where is accessing through the value from xy a certain value on a grid with which I want to proceed. If you need more code or some plots, let me know please.
Your problem is that when you loop over xy, each value of l is a single element of your xy list, one of the tuples. The value of l in the first iteration of the loop is (3.625, 41.435), the second is (3.625, 42.435), and so on.
When you do l[b], you get 3.625. When you do l[b][b], you try to get the first element of 3.625, but that is a float, so it has no indexes. That gives you an error.
To put it another way, in the first iteration of the loop, l is the same as xy[0], so l[0] is the same as xy[0][0]. In the second iteration, l is the same as xy[1], so l[0] is the same as xy[1][0]. In the third iteration, l is equivalent to xy[2], and so on. So in the first iteration, l[0][0] is the same as xy[0][0][0], but there is no such thing so you get an error.
To get the first and second values of the tuple, using the indexing approach you could just do:
x = l[0]
y = l[1]
Or, in your case:
for l in xy:
idx = N.where(lon==l[0])[0][0]
idy = N.where(lat==l[1])[0][0]
However, the simplest solution would be to use what is called "tuple unpacking":
for x, y in xy:
idx = N.where(lon==x)[0][0]
idy = N.where(lat==y)[0][0]
This is equivalent to:
for l in xy:
x, y = l
idx = N.where(lon==x)[0][0]
idy = N.where(lat==y)[0][0]
which in turn is equivalent to:
for l in xy:
x = l[0]
y = l[1]
idx = N.where(lon==x)[0][0]
idy = N.where(lat==y)[0][0]
Related
Hi I am trying to index a range of a vector of symbols.
My first idea was to use a MatrixSymbol
A = MatrixSymbol('A',10,1)
B = Matrix(A[0:2]) # does not work!
Then I thought I could use an IndexBased, but how do I generate the submatrix B (I can't index a range)
A=IndexedBased('A')
B=Matrix([A[0],A[1]]) # works but I want to define a range
There must be a proper way to do this.
IndexedBase will give you a 1-d vector like symbol.
You could use a list comprehension with a range giving the indices:
>>> a = IndexedBase("A")
>>> Matrix([a[i] for i in range(2)])
Matrix([
[A[0]],
[A[1]]])
Since you are working in Python, you are free to modify routines to suit your needs if you want to use direct slicing on the IndexedBase:
def gi(self, slc):
if isinstance(slc, slice):
a,b,s=slc.start, slc.stop, slc.step
s = s or 1
a = a or 0
assert all(type(i) is int or i is None for i in (a,b,s))
assert b is not None
rv = []
for i in range(a,b,s):
rv.append(self[i])
return rv
return _gi(self, slc)
_gi = IndexedBase.__getitem__
IndexedBase.__getitem__ = gi
With that modification you ca now do:
>>> x = IndexedBase('x')
>>> x[0]
x[0]
>>> x[:2]
[x[0], x[1]]
(This does not attempt to handle the key words argument; it's more a proof of concept.)
Good mooring to all,
The objective is to be able to create a series of new columns by inserting x and y into the df[f'sma_{x}Vs_sma{y}'] function.
The problem that I’m having is that I’m only getting the last tuple value into the function and therefore into the data frame as you can see on the last image.
On the second part of the code, 3 examples on how the tuples values must be plug into the function. IN the examples I will be using the first 2 tuples (10,11), (10,12) and the last tuple (48,49)
Code:
a = list(combinations(range(10, 15),2))
print(a)
for index, tuple in enumerate(a):
x = tuple[0]
y = tuple[1]
print(x, y)
df[f'sma_{x}_Vs_sma_{y}'] = np.where(ta.sma(df['close'], lenght = x) > ta.sma(df['close'], lenght = y),1,-1)
Code Examples:
Tuple (10,11)
df[f'sma_{10}_Vs_sma_{11}'] = np.where(ta.sma(df['close'], lenght = 10) > ta.sma(df['close'], lenght = 11),1,-1)
Tuple (10,12)
df[f'sma_{10}_Vs_sma_{12}'] = np.where(ta.sma(df['close'], lenght = 10) > ta.sma(df['close'], lenght = 12),1,-1)
Tuple (13,14)
df[f'sma_{13}_Vs_sma_{14}'] = np.where(ta.sma(df['close'], lenght = 13) > ta.sma(df['close'], lenght = 14),1,-1)
Error code
On the next lines the code that solve the issue. Although looking backwards seams very easy, it took me some time to get to the answer.
Thanks to the people that comment on the issue
a = list(combinations(range(5, 51),2))
print(a)
for x, y in a :
df[f'hma_{x}_Vs_hma_{y}'] = np.where(ta.hma(df['close'], lenght = x) > ta.hma(df['close'], lenght = y),1,-1)
The code :
import pandas as pd
import numpy as np
import csv
data = pd.read_csv("/content/NYC_temperature.csv", header=None,names = ['temperatures'])
np.cumsum(data['temperatures'])
printcounter = 0
list_30 = [15.22]#first temperature , i could have also added it by doing : list_30.append(i)[0] since it's every 30 values but doesn't append the first one :)
list_2 = [] #this is for the values of the subtraction (for the second iteration)
for i in data['temperatures']:
if (printcounter == 30):
list_30.append(i)
printcounter = 0
printcounter += 1
**for x in list_30:
substract = list_30[x] - list_30[x+1]**
list_2.append(substraction)
print(max(list_2))
Hey guys ! i'm really having trouble with the black part.
**for x in list_30:
substract = list_30[x] - list_30[x+1]**
I'm trying to iterate over the elements and sub stracting element x with the next element (x+1) but the following error pops out TypeError: 'float' object is not iterable. I have also tried to iterate using x instead of list_30[x] but then when I use next(x) I have another error.
for x in list_30: will iterate on list_30, and affect to x, the value of the item in the list, not the index in the list.
for your case you would prefer to loop on your list with indexes:
index = 0
while index < len(list_30):
substract = list_30[index] - list_30[index + 1]
edit: you will still have a problem when you will reach the last element of list_30 as there will be no element of list_30[laste_index + 1],
so you should probably stop before the end with while index < len(list_30) -1:
in case you want the index and the value, you can do:
for i, v in enumerate(list_30):
substract = v - list_30[i + 1]
but the first one look cleaner i my opinion
if you`re trying to find ifference btw two adjacent elements of an array (like differentiate it), you shoul probably use zip function
inp = [1, 2, 3, 4, 5]
delta = []
for x0,x1 in zip(inp, inp[1:]):
delta.append(x1-x0)
print(delta)
note that list of deltas will be one shorter than the input
I want to get border of data in a list using python
For example I have this list :
a = [1,1,1,1,4,4,4,6,6,6,6,6,1,1,1]
I want a code that return data borders. for example:
a = [1,1,1,1,4,4,4,6,6,6,6,6,1,1,1]
^ ^ ^ ^
b = get_border_index(a)
print(b)
output:
[0,4,7,12]
How can I implement get_border_index(lst: list) -> list function?
The scalable answer that also works for very long lists or arrays is to use np.diff. In that case you should avoid a for loop at all costs.
import numpy as np
a = [1,1,1,1,4,4,4,6,6,6,6,6,1,1,1]
a = np.array(a)
# this is unequal 0 if there is a step
d = np.diff(a)
# boolean array where the steps are
is_step = d != 0
# get the indices of the steps (first one is trivial).
ics = np.where(is_step)
# get the first dimension and shift by one as you want
# the index of the element right of the step
ics_shift = ics[0] + 1
# and if you need a list
ics_list = ics_shift.tolist()
print(ics_list)
You can use for loop with enumerate
def get_border_index(a):
last_value = None
result = []
for i, v in enumerate(a):
if v != last_value:
last_value = v
result.append(i)
return result
a = [1,1,1,1,4,4,4,6,6,6,6,6,1,1,1]
b = get_border_index(a)
print(b)
Output
[0, 4, 7, 12]
This code will check if an element in the a list is different then the element before and if so it will append the index of the element to the result list.
from numpy import *
import collections
array = [28000,35200,35200,35200,35700,36000]
rng = range(35000,37000)
for elem in array:
print elem
35200 35700 36000
That gets me off to a good start, but I need only the duplicates from the range list, which would only be 35200. I tried adding a line under print elem, for example-
print elem
print [x for x, y in collections.Counter(a).items if y > 1]
But I get TypeError: 'numpy.float64' object is not iterable. The duplicate will be needed later for an equation. How can I narrow array down to just the duplicate within a range?
items is a function, you forgot the ():
counterItems = collections.Counter(a).items()
print [x for x, y in counterItems if y > 1]
Another way to do it:
In [15]: a = [28000,35200,35200,35200,35700,36000]
In [16]: set([x for x in a if a.count(x) > 1])
Out[16]: set([35200])
The numpy way of doing it will be:
>>> a=np.array([28000,35200,35200,35200,35700,36000])
>>> a[np.sum(a==a[...,np.newaxis], axis=1)>1]
array([35200, 35200, 35200])
>>> np.unique(a[np.sum(a==a[...,np.newaxis], axis=1)>1])
array([35200])
Under the assumption of a being sorted, this is probably the fastest way (with numpy), including the range restriction:
import numpy
a = numpy.array([28000,35000,35200,35200,35200,35200,35700,36000])
left = a.searchsorted(35000, "left")
right = a.searchsorted(37000, "right")
section = a[left:right]
numpy.unique(section[section[1:] == section[:-1]])
#>>> array([35200])
Similar speedups can be found by using the bisect module on regular non-numpy arrays.