Loop the below way in python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a column 'Distance' with value from 0 to n. I want to write a loop such that, if distance is above 0.5km it should say M1. When it is less than 0.5, it should be H1. When it crosses 0.5 again it should give M2.
My dataset:
Expected output:
How can i do this?

Here is an algorithm to get you started. Improve it to suit your needs
df = pd.read_csv("input.csv")
m_count = 0
h_count = 0
current = "H"
status_halt = []
for idx in df.index:
if df["Distance_km"][idx] < 0.5:
if current == "M":
h_count += 1
status_halt.append(f"H{h_count}")
current = "H"
elif df["Distance_km"][idx] > 0.5:
if current == "H":
m_count += 1
status_halt.append(f"M{m_count}")
current = "M"
df["Status_halt"] = status_halt

Related

Running this code results in an empty list, could someone possibly see an error in my code? Thanks [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
def every_payday(year):
# this method will get every "weekly" payday for the given year
d = date(year, 1, 1)
d += timedelta(days = 4 - d.weekday())
while d.year == year:
yield d
d += timedelta(days = 7) # since payday is weekly or every 7 days
# getting the date for today and defining a table to append the list of paydays to
today = date.today() # current day
table = []
for d in every_payday(2022):
table.append(d.strftime("%Y-%m-%d"))
print(table)
When giving 2022
# d is 2022-01-01
d = date(year, 1, 1)
# remove 1d, as d.weekday() is 5, so remove 4-5=-1
d += timedelta(days=4 - d.weekday())
# d is 2021-12-31
# 2021 != 2022 : code ends
while d.year == year:

show function approaches certain value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
the following is my code for to solve this question :
wrote three functions to Show that as n increases (e.g. with a doubling experiment), from n = 2 to n = 1,000, the value of “day_sim(n)” approaches “sqrt(pi * n / 2)”.
"show that is approaching “sqrt(pi * n / 2)” -> but the graph doesn't look like it is approaching to such sqrt value at all...
Please help me with cracking this
import random
from random import randint
import numpy as np
def randomgen(n):
np.random.randint(low = 0, high = n)
return random.randint(0,n-1)
randomgen(100)
def day(n):
result = []
random = randomgen(n)
count =0
while random not in result:
result.append(random)
random = randomgen(n)
count += 1
return count
day(100)
def day(n):
result = []
random = randomgen(n)
count =0
while random not in result:
result.append(random)
random = randomgen(n)
count += 1
return count
def day_sim(n):
n_trails = 10000
for n in range(2,n_trails,50):
sq_rt = math.sqrt(math.pi*n/2)
day_sim = day(n)
print("n =",n,"Absolute difference=",abs(sq_rt - day_sim),"SQ value",sq_rt)
plt.scatter(n,day_sim, color='skyblue')
plt.scatter(n,sq_rt, color='red')
plt.xlim(0,10000)
plt.ylim(0,200)
day_sim(n_trails)
enter image description here
One way to do this would be to plot the variance as you progress:
variance = the (x - y^)**2/n
results = []
for n in range(2000):
y = day_sim(n)
x = (math.pi*n/2)**.5
variance = (x-y)**2/n
results.append((n, variance))
then plot the results and you should see the variance approach zero

Index pandas dataframe rows 4 at a time [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to to be able to something along the lines of:
for i in range(0, len(df), 4):
curr = pd.DataFrame()
vcch = int(df.loc[i, 'IN_CUSTOM_SELECT'])
icch = int(df.loc[i+1, 'IN_CUSTOM_SELECT'])
vccl = int(df.loc[i+2, 'IN_CUSTOM_SELECT'])
iccl = int(df.loc[i+3, 'IN_CUSTOM_SELECT'])
idlpwr = (vcch * icch) + (vccl * iccl)
idlpwr = idlpwr / (10**6)
where I do some calculations based on the specific values of columns in combinations of rows of 4.
If you're just working with a regular autonumbered index, one easy option is to reshape your data and use pandas vectorized operations for the math:
In [196]: df = pd.DataFrame({'IN_CUSTOM_SELECT': np.random.random(24)})
In [197]: reshaped = df.set_index([df.index.map(lambda x: x // 4), df.index.map(lambda x: x % 4)]).unstack()['IN_CUSTOM_SELECT']
In [198]: reshaped['idlpwr'] = ((reshaped[0] * reshaped[1]) + (reshaped[2] * reshaped[3])) / 10**6
In [199]: reshaped
Out[199]:
0 1 2 3 idlpwr
0 0.788758 0.853356 0.627796 0.355143 8.960487e-07
1 0.312111 0.602934 0.908984 0.046183 2.301622e-07
2 0.842201 0.507629 0.541432 0.592680 7.484218e-07
3 0.506601 0.605108 0.497627 0.362006 4.866923e-07
4 0.308097 0.991945 0.822433 0.272082 5.293851e-07
5 0.573716 0.852356 0.009606 0.961437 4.982462e-07

Working with two Two-dimensional arrays in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
my_list = [['Chris',33,'JAN'],['Katia',40,'JAN'],['Petunia',54,'JAN'],['Clee',26,'JAN'],['katt',73,'JAN'],['battt',83,'JAN'],['FRIES',59,'FEB'],['GGEEZ',89,'FEB'],['SHEEESH',25,'MAR']]
threshold = [[217, 'JAN'], [104, 'FEB'], [18, 'MAR']]
output: [['Chris','Katia','Petunia','Clee','katt'],['FRIES','GGEEZ'],['SHEEESH']]
I want to make a new list with the first element in the nested array (the names) until the sum of the second elements in the nested array passes the 217 for JAN, 104 for FEB and 18 for MARCH.
I dont know how to do it since both of the lists are are indented and I find that hard to work with, But it should check it in a loop if my_list[2] == threshold[1] and sum the my_list[1]s until it is greater or equal to threshold[0] than it should go and check if the and check if my_list[2] == threshold[1] (but this time we skip the remaining januaries and check if the february is equal to the mylist and so on, its hard to articulate
Try:
my_list = [['Chris',33,'JAN'],['Katia',40,'JAN'],['Petunia',54,'JAN'],['Clee',26,'JAN'],['katt',73,'JAN'],['battt',83,'JAN'],['FRIES',59,'FEB'],['GGEEZ',89,'FEB'],['SHEEESH',25,'MAR']]
threshold = [[217, 'JAN'], [104, 'FEB'], [18, 'MAR']]
results = []
for max_num, month in threshold:
accumulator = []
count = 0
for s, num, month_ in my_list:
if month == month_ and count < max_num:
accumulator.append(s)
results.append(accumulator)
print(results)
output:
[['Chris', 'Katia', 'Petunia', 'Clee', 'katt', 'battt'], ['FRIES', 'GGEEZ'], ['SHEEESH']]
output = []
for a,b in threshold:
sum = 0
curr = []
for x,y,z in my_list:
if z == b and sum < a:
sum += y
curr.append(x)
output.append(curr)

Is there a way for me to find a value's index/location within a pandas DataFrame? (python) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to style a value and a value next to it in a pandas dataframe:
pandas_chart_sorted = pd.DataFrame({'Palabras': {0: 'papa', 1: 'pepe', 2: 'ja'}, 'Apariciones': {0: 2, 1: 2, 2: 1}})
def filter_mark(val):
if val in self.filters:
color = 'red'
else:
color = 'black'
return 'color: {}'.format(color)
pandas_chart_sorted = pandas_chart_sorted.style.applymap(filter_mark)
with pd.ExcelWriter(self.new_path) as writer:
pandas_chart_sorted.to_excel(writer)
but I can't manage to style the value right next to it.
So the output is
this but it should look like this.
How can I do it?
Try this method:
df = pd.DataFrame(np.arange(25).reshape(5, -1))
def filter_mark(row):
s = (row % 6 == 0) | (row.shift() % 6 == 0)
return [f'color: red' if i != False else '' for i in s]
def filter_row(row):
return ['background: yellow'if (row % 10 == 0).any() else '' for _ in row]
df.style.apply(filter_mark, axis=1).apply(filter_row, axis=1)
Output:

Categories