While Loop with 2 variables in Python [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the value of y after the following statements?
x = 100
y = 0
while x > 50:
y = y + 1
x = x - 1
I'm having trouble with questions that involve 2 variables.

Step through the first few iterations of the loop, look for a pattern, and extrapolate.
x = 100 # x = 100
y = 0 # x = 100 y = 0
if x > 50: # x = 100 y = 0
y = y + 1 # x = 100 y = 1
x = x - 1 # x = 99 y = 1
if x > 50: # x = 99 y = 1
y = y + 1 # x = 99 y = 2
x = x - 1 # x = 98 y = 2
if x > 50: # x = 98 y = 2
y = y + 1 # x = 98 y = 3
x = x - 1 # x = 97 y = 3
if x > 50: # x = 97 y = 3
y = y + 1 # x = 97 y = 4
x = x - 1 # x = 96 y = 4
if x > 50: # x = 96 y = 4
y = y + 1 # x = 96 y = 5
x = x - 1 # x = 95 y = 5
if x > 50: # x = 95 y = 5
y = y + 1 # x = 95 y = 6
x = x - 1 # x = 94 y = 6
...
if x > 50: # x = 52 y = 48
y = y + 1 # x = 52 y = 49
x = x - 1 # x = 51 y = 49
if x > 50: # x = 51 y = 49
y = y + 1 # x = 51 y = 50
x = x - 1 # x = 50 y = 50
if x > 50: # x = 50 y = 50
(false, end process)

Related

limiting data set to be used xlim

I have lots of files that contain x, y, yerr columns. I read them and save and apply a change on the x values, then I would like to set a limit on the x values I will use afterwards which are the newxval:
for key, value in files_data.items():
file_short_name = key
D_value_sale = value[1]
data = pd.DataFrame(value[0])
if data.shape[1] == 3:
data.columns = ["x", "y", "yerr"]
else:
data.columns = ["x", "y"]
D = D_value_sale
b = 111
c = 222
data["newx"] = -c*(((data.x*(1/(1+D)))-b)/b)
data["newy"] = (data.y-data.y.min())/(data.y.max()-data.y.min())
w = data[(data.newx < 20000) & (data.newx > 8000)]
dfx = w["newx"]
dfy = w["newy"]
peak = GaussianModel()
pars = offset.make_params(c=np.median(dfy))
pars += peak.guess(dfy, x= dfy, amplitude=-0.5)
result = model.fit(dfy, pars, dfx)
If I'm understanding correctly what you are asking this is what you could do:
for key, value in files_data.items():
file_short_name = key
# main = value[1]
data = pd.DataFrame(value[0])
if data.shape[1] == 3:
data.columns = ["x", "y", "yerr"]
else:
# Here you should define what happens in case
# the data isn't what you expected it to be
data["newx"] = data.x + 1 # Perform whatever transformation you need
# data["newy"] = data.y * (1.01234) # Etc.
# Then you can limit the newx column by doing:
data[(data.newx < upper_limit) & (data.newx > lower_limit)]
What you're doing won't work if you want to preserve the relationship between columns. When you assign the data columns to their own variables xval, yval and error you are implicitely "losing" their relationship.
I'll open with the same caveat of "if I'm understanding you correctly" then the crux of what you are looking for is the boolean array that you have created to apply your limits:
data = data[(data[0] >= xlim[0]) & (data[0] <= xlim[1])]
This boolean array can be saved and applied to any array of the same shape.
idx = (data[0] >= xlim[0]) & (data[0] <= xlim[1])
filtered_data = data[0][idx]
filtered_newxval = newxval[idx]
By way of a more complete and independent example, see the code below where this concept can be applied to multidimensional arrays and pandas dataframes
import numpy as np
import pandas as pd
np.random.seed(42)
x = np.random.randint(0, 20, 10)
y = np.random.randint(0, 20, 10)
print("x", x)
# >>> x [ 6 19 14 10 7 6 18 10 10 3]
print("y", y)
# >>> y [ 7 2 1 11 5 1 0 11 11 16]
xmin = 3
xmax = 17
idx = (x >= xmin) & (x <= xmax)
data = np.vstack((x, y))
print("filtered_data:\n", data[:, idx])
# >>> filtered_data:
# [[ 6 14 10 7 6 10 10 3]
# [ 7 1 11 5 1 11 11 16]]
df = pd.DataFrame({"x": x, "y": y})
df["xnew"] = df["x"] * 2
print(df[idx])
# >>> x y xnew
# >>> 0 6 7 12
# >>> 2 14 1 28
# >>> 3 10 11 20
# >>> 4 7 5 14
# >>> 5 6 1 12
# >>> 7 10 11 20
# >>> 8 10 11 20
# >>> 9 3 16 6

Multiplication table with X's while using functions?

Comp sci student here,
Very lost on how to add those X's on a multiplication table like the added photo. https://i.stack.imgur.com/cdHoZ.png
How on earth would I add those X's while also using functions? Here's my code if this helps:
for i in range(1,11):
for j in range(1,11):
print(i * j, end='\t')
print('')
The rule for the X is i>3 and j>2 and i*j != 81
for i in range(1, 10):
for j in range(1, 10):
if i > 3 and j > 2 and i * j != 81:
print('X', end='\t')
else:
print(i * j, end='\t')
print()
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 X X X X X X X
5 10 X X X X X X X
6 12 X X X X X X X
7 14 X X X X X X X
8 16 X X X X X X X
9 18 X X X X X X 81

Merge multiple Series as a single column into a DataFrame

I have the following data frames:
A.
k m n
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
5 x x x
6 x x x
7 x x x
8 x x x
9 x x x
B1.
l i j
1 x 46 x
2 x 64 x
3 x 83 x
9 x 70 x
B2.
l i j
0 x 23 x
4 x 34 x
6 x 54 x
8 x 32 x
B3.
l i j
0 x 11 x
5 x 98 x
7 x 94 x
9 x 80 x
How can I add the column "i" (from data frames B1, B2, and B3) to the data frame A?
Regarding the duplicate values (e.g. index 9 in B1 and B3 & index 0 in B2 and B3), I want to keep the leftmost value from [B1, B2, B3] (e.g. 23 for index 0 & 70 for index 9).
A desired output would be:
k m n i
0 x x x 23
1 x x x 46
2 x x x 64
3 x x x 83
4 x x x 34
5 x x x 98
6 x x x 54
7 x x x 94
8 x x x 32
9 x x x 70
you can concat the Bx dataframes, and use duplicated on the index to remove the duplicated index and keep the first.
A['i'] = (pd.concat([B1, B2, B3])
.loc[lambda x: ~x.index.duplicated(keep='first'), 'i'])
print(A)
k m n i
0 x x x 23
1 x x x 46
2 x x x 64
3 x x x 83
4 x x x 34
5 x x x 98
6 x x x 54
7 x x x 94
8 x x x 32
9 x x x 70

UnboundLocalError: local variable 'y' referenced before assignment in Pandas

I am trying to apply one funtion to a column but i am getting the error
Name weight
Person1 30
Person2 70
My code is below
def classify(x):
if 0 <= x < 20:
y = "0 to 20%"
if 20 < x < 40:
y = "20 to 40%"
if 40 < x < 60:
y = "40 to 60%"
if 60 < x < 80:
y = "60 to 80%"
if 80 < x <= 100:
y = "80 to 100%"
return ( y)
df['Target'] = df['weight'].apply(lambda x: classify(x)) throwing the Local bound error
If I use print instead of return I am able to see the outputs
Expected out
Name weight Target
Person1 30 20 to 40
Person2 70 60 to 80
Why not using cut
df['Target']=pd.cut(df['weight'],[0,20,40,60,80,100])

Zero assignement in inline comparison

Example:
>>> x = 10
>>> x = x > 9 and 0 or x
>>> x
10
while:
>>> x = 10
>>> x = x > 9 and 1 or x
>>> x
1
Obviously 0 is treated as boolean False. How to use inline comparison to assign integer 0?
You probably want this
x= 0 if x > 9 else x
This is the python way of traditional ternary operators in c like languages.
The code snippet that you have will always give x or 1 for x > 9:
x = x > 9 and 0 or x
This is interpreted as
x = (x > 9 and 0) or x
x = 0 or x
x = x
The other version
x = x > 9 and 1 or x
is interpreted as
x = (x > 9 and 1) or x
x = 1 or x # or gets short-circuited so second expression is not evaluated
x = 1
try this:
x = 0 if x > 9 else x

Categories