numpy array summary with for loop - python

I have a lot of txt, I want to read it, and plus them(every txt have same shape of array)
for i in base_n:
dfp_base=np.loadtxt(base_n,skiprows=2,usecols=(1,2,3))
dfp_base+=dfp_base
print dfp_base
but it's will only plus the end of files
I try to assign a variable but it's will give me an error
for i in base_n:
dfp_base=np.loadtxt(base_n,skiprows=2,usecols=(1,2,3))
dfp_base_s+=dfp_base
print dfp_base_s
UnboundLocalError: local variable 'dfp_base_s' referenced before assignment
how to fix it?
EDIT
i define a zero array and solve this problem
dfp_base_s=np.zeros(shape=(30,3))

your problem that you are trying to assign to var that not referenced before assignment
see on below:
for i in range(1,10):
dfp_base=1
dfp_base_s+=dfp_base
NameError Traceback (most recent call last)
<ipython-input-2-24596062a447> in <module>
1 for i in range(1,10):
2 dfp_base=1
----> 3 dfp_base_s+=dfp_base
4
NameError: name 'dfp_base_s' is not defined
but if you initialize before the loop that will work
dfp_base_s = 0
for i in range(1,10):
dfp_base=1
dfp_base_s+=dfp_base
dfp_base_s
9

Related

How to execute a string as a variable within a function or a for loop?

Lets say I have the following function
def code_string(a):
for i in range(a):
exec('f=a+i')
print(f)
When I run it in the using the following command
code_string(3)
It gives me the following error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-9c91de8067f3> in <module>()
----> 1 code_string(3)
<ipython-input-2-2ae9915b0a25> in code_string(a)
2 for i in range(a):
3 exec('f=a+i')
----> 4 print(f)
NameError: name 'f' is not defined
when I run it not in the function as so
a=3
for i in range(a):
exec('f=a+i')
print(f)
It works perfectly fine as so
3
4
5
Why is this happening and can I execute a string code within a function in python
NOTE: This is only a demo example, please do not expect my code to be as simple as this demo example. I just put it to demonstrate the problem.
You can try this:
def code_string(a):
for i in range(a):
exec('f=a+i', locals(), globals())
print(f)

Unexpected Python for-loop behaviour?

Can someone explain what happened in the second run ? Why did I get a stream of 9's when the code should have given an error?
>>> for __ in range(10): #first run
... print(__)
...
0
1
2
3
4
5
6
7
8
9
This was the second run
>>> for __ in range(10): #second run
... print(_)
...
9
9
9
9
9
9
9
9
9
9
>>> exit()
After this, when I ran the code for the third time, the same code executed as expected and gave the below error. I realize that this question has no practical use. But, I would really like to know why it happened?
NameError: name '_' is not defined
The _ variable is set in the Python interpreter, always holding the last non-None result of any expression statement that has been run.
From the Reserved Classifiers and Identifiers reference:
The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module.
and from sys.displayhook():
If value is not None, this function prints repr(value) to sys.stdout, and saves value in builtins._. [...] sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session.
Here, that result was 9, from an expression you must have run before the code you shared.
The NameError indicates you restarted the Python interpreter and did not yet run an expression statement yet that produced a non-None value:
>>> _
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> 3 * 3
9
>>> _
9

Python error: Valueerror-need-more-than-1-value-to-unpack

In python when I run this code:
lat, lon = f.variables['latitude'], f.variables['longitude']
latvals = lat[:]; lonvals = lon[:]
def getclosest_ij(lats,lons,latpt,lonpt):
dist_sq = (lats-latpt)**2 + (lons-lonpt)**2
minindex_flattened = dist_sq.argmin()
return np.unravel_index(minindex_flattened, lats.shape)
iy_min, ix_min = getclosest_ij(latvals, lonvals, 46.1514, 20.0846)
It get the following error:
ValueError Traceback (most recent call last)
ipython-input-104-3ba92bea5d48 in module()
11 return np.unravel_index(minindex_flattened, lats.shape)
12 iy_min, ix_min = getclosest_ij(latvals, lonvals, 46.1514, 20.0846)
ValueError: need more than 1 value to unpack
What does it mean? How could I fix it?
I would read a NetCDF file, it is consist of total coloumn water data with dimensions: time(124), latitude(15), and longitude(15). I would appropriate the amount of tcw for specific point (lat,lon), and time. I tried to use the code above to solve the first part of my task to evaluate the tcw for specific coorinates, but didn't work.
Thank your help in advance.
in python you can write
var1, var2 = (1, 2) # = iterable with 2 items
that will store 1 in var1 and 2 in var2.
This feature is called unpacking.
So the error your code throws means, that the function getclosest_ij returned one value instead of the 2 values you would need to unpack them into iy_min and ix_min

Trouble with for loops

We just learned for loops in class for about five minutes and we were already given a lab. I am trying but still not getting what I need to get. What I am trying to do is take a list of integers, and then only take the odd integers and add them up and then return them so if the list of integers was [3,2,4,7,2,4,1,3,2] the returned value would be 14
def f(ls):
ct=0
for x in (f(ls)):
if x%2==1:
ct+=x
return(ct)
print(f[2,5,4,6,7,8,2])
the error code reads
Traceback (most recent call last):
File "C:/Users/Ian/Documents/Python/Labs/lab8.py", line 10, in <module>
print(f[2,5,4,6,7,8,2])
TypeError: 'function' object is not subscriptable
Just a couple of minor mistakes:
def f(ls):
ct = 0
for x in ls:
# ^ Do not call the method, but just parse through the list
if x % 2 == 1:
ct += x
return(ct)
# ^ ^ parenthesis are not necessary
print(f([2,5,4,6,7,8,2]))
# ^ ^ Missing paranthesis
You're missing the parenthesis in the function call
print(f([2,5,4,6,7,8,2]))
rather than
print(f[2,5,4,6,7,8,2])

why i get this traceback?

This is part of my code:
if ind_1<>0:
rbrcol=[]
brdod1=[]
for i in range(27):
if Add_Cyc_1[1,i]!=0:
rbrcol.append(Add_Cyc_1[0,i])
brdod1.append(Add_Cyc_1[1,i])
Probrani_1=vstack((rbrcol,brdod1))
pok=0
for i in (rbrcol):
pok+=1
broj1=0
for j in range(21):
if SYS_STATE_1[i,j]==0:
broj1+=1
if broj1 <= Probrani_1[1,pok-1]:
SYS_STATE_1[i,j]=123456
And when i run program i get this:
Traceback (most recent call last):
File "C:/Python26/pokusaj2.py", line 157, in <module>
for i in (rbrcol):
NameError: name 'rbrcol' is not defined
What i do wrong???
I think the real problem is the if at the very top. Your indenting is incorrect - the code as written won't run because the line after the if is not indented.
Assuming it is indented in the original code, then rbrcol is not initialized if ind_1 is 0 and as ghostdog says if the if statement never fires, then rbrcol would not be set at all.
just as the error says, "rbrcol" doesn't have value. check your for loop
for i in range(27):
if Add_Cyc_1[1,i]!=0: <----- this part doesn't get through
rbrcol.append(Add_Cyc_1[0,i])
brdod1.append(Add_Cyc_1[1,i])
Probrani_1=vstack((rbrcol,brdod1))
also, what is Add_Cyc_1 ? To assign multidimension list
Add_Cyc_1[1,i] should be Add_Cyc_1[1][i]
further, this
if ind_1<>0: <<--- if this is not true, then rbrcol will not be defined
rbrcol=[] << --- <> should be != , although <> its also valid, but now ppl use !=
brdod1=[]

Categories

Resources