I have looked at this Q/A Intent of this Fotran77 code and I have almost converted the below Fortran77 style code into Python 3.x except I had a doubt where the i = i + 1 should be placed in the Python version. As mentioned in the comments of the linked question I have done the conformance tests and the results are off by a margin of 2. Hence the question.
i = 0
500 continue
i = i +1
if (i .le. ni) then
if (u(i,j-1) .gt. -9999.) then
r(1,j) = u(i,j-1)
go to 600
else
missing = i
go to 500
end if
end if
600 continue
Here is my Python version
i = 0
while (i <= ni):
i = i+1
if (u[i,j-1] > -9999.0):
r[0,j] = u[i,j-1]
break
else:
missing = i
Did I place the increment counter at the right location ?
Directly translating is not advised because you loose a number of nice efficient coding features of python.
To do this properly in python you should 1) recognize the 0- index convention of python, and 2 ) recognize that that fortran is column major and python is row major so you should reverse the index ordering for all multi-dimensional arrays.
If you do that the loop can be written:
try:
r[j,0]=[val for val in u[j] if val > -9999 ][0]
missing=False
except:
missing=True
I'm assuming we don't actually need the numeric value of missing.
If you need it you will have something like this:
try:
missing,r[j,0]=[(index,val) for (index,val) in enumerate(u[j]) if val > -9999 ][0]
except:
missing=-1
You could also use next which would be faster, but it gets a little trickier handling the missing condition.
Related
I am trying to iterate through dataframe rows and set a new column to either a 1 or 0 depending on conditions. Up to the if statement works fine, but once the elif section is added it gives me an "index out of bounds error". Any ideas on how to remedy this?
low=history.low
high = history.high
history['bottom'] = " "
history['top']=" "
for i in range(len(history)):
if (low[i] < low[i-1]) and (low[i] < low[i-2]) and (low[i] < low[i+1]) and (low[i] < low[i+2]) :
history['bottom'][i] = 1
elif (high[i] > high[i-1]) and (high[i] > high[i-2]) and (high[i] > high[i+1]) and (high[i] > high[i+2]):
history['top'][i]=1
else:
history['top'][i] = 0
history['bottom'][i] = 0
One of our error is explained by #Code-Apprentice
Other which I found and I think you are looking for this is that in lines
history['bottom'][i] = 1 and history['top'][i]=1 you are trying to change the value of an index which may not be present in it.
For example if i = 1 then the lines specified above will generate error as index 1 is not present in them. (They only have index 0).
Instead of using index to change values you can use .append to add values
It's because this is trying to access an index that doesn't exist. I would like to see more of the code above to know what history.low and history.high is referring to for the value.
But have you gotten any results before the error?
Also, please explain len(history). In your code there is a history dictionary where you have history['bottom'] = " " and history['top']=" ", but at the same time you have low=history.low and high = history.high. What's the difference between these two history objects/variables?
Please show more of your code.
This code gives me an indentation error on checks. I get that this happens often, but the instance is in between two for loops that exist because I need to reference two different lists.
I do not even have the data set made yet, but it should report that the syntax is correct at least. The code is fairly simple. I want to automate package placement in a building and I want to do so by taking the biggest packages and putting them in place with the least amount of room where it would still fit.
All inputs that I used so far are dictionaries because I need to know which shelf I am referring too. I am this close to turning it to lists and being extremely strict about formatting.
inv = maxkey["Inventory"]
is the line where the mistake happens. I do not know how to fix it. Should I use lists for this project instead? Is there a flaw in the logic? Is there a parentheses I forgot? Please let me know if this is just an oversight on my part. Please contact me for further details.
def loadOrder(inProd, units, loc, pref, shelves):
items = len(inProd)
while items > 0
# What is the biggest package in the list?
mxw = 0 # Frontal area trackers
BoxId = {} # Identifies what is being selected
for p in inProd:
if p["Height"]*p["Width"] > mxw:
mxw = p["Width"]*p["Height"]
BoxId = p
else:
pass
# What is the location with the least amount of space?
maxi = 0.001
maxkey = {}
for key in loc:
if key["Volume Efficiency"] > maxi and key["Width"] > mxw/BoxId["Height"]:
maxi = key["Volume Efficiency"]
maxkey = key
else:
pass
maxkey["Inventory"].append(BoxId)
weight = 0
volTot = 0
usedL = 0
inv = maxkey["Inventory"]
for k in inv:
weight = k['Weight']+weight
vol = k['Height']*k['Width']*k['Depth']+volTot
usedL = k['Width']+usedL
maxkey["Volume Efficiency"] = volTot/(maxkey['Height']*maxkey['Weight']*maxkey['Depth'])
maxkey['Width Remaining'] = usedL
maxkey['Capacity Remaining'] = weight
del inProd[BoxId]
items = len(inProd)
return [inProd, units, loc, pref, shelves]
Indentation in a function definition should be like:
def function-name():
<some code>
<return something>
Also, you have missed : after while loop condition.
It shoulde be while items > 0:
And you should not mixing the use of tabs and spaces for indentation.
The standard way for indentation is 4 spaces.
you can see more in PEP 8.
So I'm trying to go through my dataframe in pandas and if the value of two columns is equal to something, then I change a value in that location, here is a simplified version of the loop I've been using (I changed the values of the if/else function because the original used regex and stuff and was quite complicated):
pro_cr = ["IgA", "IgG", "IgE"] # CR's considered productive
rows_changed = 0
prod_to_unk = 0
unk_to_prod = 0
changed_ids = []
for index in df_sample.index:
if num=1 and color="red":
pass
elif num=2 and color="blue":
prod_to_unk += 1
changed_ids.append(df_sample.loc[index, "Sequence ID"])
df_sample.at[index, "Functionality"] = "unknown"
rows_changed += 1
elif num=3 and color="green":
unk_to_prod += 1
changed_ids.append(df_sample.loc[index, "Sequence ID"])
df_sample.at[index, "Functionality"] = "productive"
rows_changed += 1
else:
pass
print("Number of productive columns changed to unknown: {}".format(prod_to_unk))
print("Number of unknown columns changed to productive: {}".format(unk_to_prod))
print("Total number of rows changed: {}".format(rows_changed))
So the main problem is the changing code:
df_sample.at[index, "Functionality"] = "unknown" # or productive
If I run this code without these lines of code, it works properly, it finds all the correct locations, tells me how many were changed and what their ID's are, which I can use to validate with the CSV file.
If I use df_sample["Functionality"][index] = "unknown" # or productive the code runs, but checking the rows that have been changed shows that they were not changed at all.
When I use df.at[row, column] = value I get "AttributeError: 'BlockManager' object has no attribute 'T'"
I have no idea why this is showing up. There are no duplicate columns. Hope this was clear (if not let me know and I'll try to clarify it). Thanks!
To be honest, I've never used df.at - but try using df.loc instead:
df_sample.loc[index, "Functionality"] = "unknown"
You can also iat.
Example: df.iat[iTH row, jTH column]
I'm pretty new to coding, so forgive me if this is super obvious.
When running a while loop, and I want to only run if for a certain amount of times. Ex (python):
question_var = 0
while True:
if condition:
question_var += 1
continue
print("Condition not met")
I want to know if there is a proper variable to use in place of question_var. Similar to how i is used to represent index in a for loop. I understand that this is not necessary, but I just want to learn how to do it right. I have been using a variable named rev
Here is the actual program I am trying to run:
rev = 0
while rev <= 10:
new_file_name = "C# is bad ({}).txt".format(rev)
with open(new_file_name, 'w') as tempfile:
tempfile.write("C# is bad.\nPython is good.\n")
rev += 1
its a gag I made for my friend who likes C#, but when I was making it I felt the the variable rev seemed unprofesional.
using a while True loop is useful in some cases, but it is often not the most idiomatic use in python. As mentioned in the comments, you might find a for loop more appropriate:
for rev in range(0, 11):
new_file_name = "C# is bad ({}).txt".format(rev)
with open(new_file_name, 'w') as tempfile:
tempfile.write("C# is bad.\nPython is good.\n")
Also, you don't really need to use format() here, you could change the second line to:
new_file_name = f"C# is bad ({rev}).txt"
The code follows should be a working approach if you're using Python 3.8, but I can't test it currently since I'm on my phone
counter = 0
maxLoops = 10
while (counter := counter++) < maxLoops:
# do some magic
But a better approach is to use a for loop if you want to loop a certain amount.
maxLoops = 10
for i in range(maxLoops):
# do some magic
But there is no convention for how to run a while loop for a certain amount.
For the first part of the question you could use for and break:
need=2
for i in range(0,11):
if i%3 == 0:
print(i)
need -= 1
if need <= 0:
break
print("i is {} after the loop".format(i))
Output:
0
3
i is 3 after the loop
This loop will run at most 11 times, but finishes immediately when it finds the two special values it is looking for. Also, the loop variable remains accessible after the loop. Yeah, Python is different from C# here.
However, and this leads to the second part of the question, not knowing this means that you may rather want to implement something like this:
for rev in range(0, 11):
new_file_name = "Python is new to me ({}).txt".format(rev)
with open(new_file_name, 'w') as tempfile:
tempfile.write("I will learn Python first.\nAnd even then I will not speak nonsense.\n")
I'm implementing HR module in OpenERP I am trying to setup a condition in Salary Head like:
if Basic > 0 and basic <=5000:
ProfessionalTax = 80
else if
Basic > 5000 and basic <= 10000
ProfessionalTax = 150
Can anybody help me with the syntax? I have not had any luck finding this information.
The Python if statement uses elif to mean else if. Your example would be as follows:
if basic > 0 and basic <=5000:
ProfessionalTax = 80
elif basic > 5000 and basic <= 10000:
ProfessionalTax = 150
I also had to move the condition up onto the same line as elif. Remember that line breaks and white space have meaning in Python. Variable names are case-sensitive, so I guessed that you only had one variable named basic and made them all the same.