Python looping past values it shouldn't be [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
This is a follow up question (?) to a post I made yesterday: Python pandas df.loc not being found in a table
I'm trying to I'm trying to find a certain row and column in a given .csv file with pandas. Here is a snapshot of the table: Table
The table goes from 1/1/2015 to 12/31/2017. I've located the specific column and date I want to use from the csv file, and printing it so I can see if it's working properly. This is the code I have thus far:
months = {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12}
month = str(input('Enter a month: '))
year = str(input('Enter a year: '))
if not (2015 <= float(year) <= 2017):
print('Enter a year bewteen 2015 and 2017, both included and try again')
exit()
day = 1
df1 = df.set_index(['Date'])
if (month == 'January' or 'March' or 'May' or 'July' or 'August' or 'October' or 'December'):
while day < 32:
find = df1.loc[[str(months[month]) + '/' + str(day) + '/' + str(year)], ['Temp Low']]
print(find)
day += 1
elif (month == 'April' or 'June' or 'September' or 'November'):
while day < 31:
find = df1.loc[[str(months[month]) + '/' + str(day) + '/' + str(year)], ['Temp Low']]
print(find)
day += 1
elif (month == 'February'):
if year == '2016':
while day < 29:
find = df1.loc[[str(months[month]) + '/' + str(day) + '/' + str(year)], ['Temp Low']]
print(find)
day += 1
else:
while day < 28:
find = df1.loc[[str(months[month]) + '/' + str(day) + '/' + str(year)], ['Temp Low']]
print(find)
day += 1
This code is working correctly for months with 31 days, but breaks for any other month. For example if I enter "June" for the month (no quotations), the code works until it reaches day 30, then tries to look for day 31. Why is this happening? It seems to be searching for day 31 in the date column even though I've restricted it to be less than 31.
Picture of error code:
Error

Your or statements are plain wrong.
if (month == 'January' or 'March' or 'May' or 'July' or 'August' or 'October' or 'December'):
always evaluates to true; you'll want to replace that idiom with e.g.
if month in ('January', 'March', 'May', 'July', 'August', 'October', 'December'):

It's as simple as changing your if and elif statements.
if (month == 'January' or 'March' or 'May' or 'July' or 'August' or 'October' or 'December'):
think of the or statement as another if: you have to compare it to the month again.
In other words: in your if statement, you're literally saying "if month is equal to January or if march or if May or if July ..." As we know, If 'July' really doesn't mean anything.
try : if month in ('January', 'March', 'May', 'July', 'August', 'October', 'December'):

Related

How to create a function that converts month values into quarter using if statement in python

I need to create a function called as convert_to_qtr() that converts monthly values in the month value of data frame into quarters. Given below is the month data frame below:-
In the convert_to_qtr() function, we should use the following if conditions:-
• If the month input is Jan-Mar, then the function returns “Q1”
• If the month input is Apr-Jun, then the function returns “Q2”
• If the month input is Jul-Sep, then the function returns “Q3”
• If the month input is Oct-Dec, then the function returns “Q4”
Then this function should be applied to Month Dataframe provided above and a new column called as Quarter should be created that contains the quarter of each observations of months(January, Feb) etc it is aligned to .
quarter = 0
excl_merged['quarter'] = excl_merged[quarter]
excl_merged
def convert_to_quarterly(excl_merged):
if excl_merged['Month'] == 'January' & excl_merged['Month'] == 'February' & excl_merged['Month'] == 'March':
print(excl_merged[quarter] == 'Q1')
elif excl_merged['Month'] == 'April' & excl_merged['Month'] == 'May' & excl_merged['Month'] == 'June':
print(excl_merged[quarter] == 'Q2')
elif excl_merged['Month'] == 'July' & excl_merged['Month'] == 'August' & excl_merged['Month'] == 'September':
print(excl_merged[quarter] == 'Q3')
else:
print(excl_merged[quarter] == 'Q4')
convert_to_quarterly(excl_merged)
I was not able to run the function properly and hence was getting errors
def convert_to_quarter( month):
months = [ 'January', 'February', 'March', 'April ', 'May', 'June', \
'July', 'August', 'September', 'October', 'November', 'December']
return months.index[ 'month'] // 3
Try the following:
def convert_to_quarterly(excl_merged):
if excl_merged['Month'] in ['January', 'February', "March"]:
excl_merged[quarter] == 'Q1'
elif excl_merged['Month'] in ["April", "May", "June"]:
excl_merged[quarter] == 'Q2'
elif excl_merged['Month'] in ['July', 'August', 'September']:
excl_merged[quarter] == 'Q3'
elif excl_merged["Month"] in ["November", "December", "December"]:
excl_merged[quarter] == 'Q4'
else:
print("Unkown month name!")
The main problem is that you are using an and statement.
A month can't be "Januar" and "Fabruary".
I would also recoment to use brackets when useing the & or | operator around the single bool operations.
At last i would recoment to use the in operator to test against all three values at one. It should be faster and the code is much easier to read.
Wouldn't it be easier to do something like:
df.Transaction_Timestamp.apply(lambda x: "Q" + str(x.quarter))
Example
import pandas as pd
import numpy as np
rng = np.random.default_rng()
df = pd.DataFrame({
"Transaction_Timestamp":pd.date_range("2022-01-01", periods=365),
"Value":rng.integers(0, 100, size=365)
})
df["Qrt"] = df.Transaction_Timestamp.apply(lambda x: "Q" + str(x.quarter))
df.head()
Transaction_Timestamp Value Qrt
0 2022-01-01 84 Q1
1 2022-01-02 43 Q1
2 2022-01-03 91 Q1
3 2022-01-04 29 Q1
4 2022-01-05 88 Q1
You need to do two things:
Create the function convert_to_qtr() that takes in a month (January, February, etc.) and returns the associated quarter. So if the month is January, return 1, if December, return 4, etc. For a month to be in the first quarter, for example, the month could be January or February or March. A month cannot be January and February and March at the same time, which is what your code is currently checking for. This function should also be taking in a month instead of a dataframe.
Apply this function to the Month column in your dataframe, and store the result in a new column called Quarter. You can do something like: df['Quarter'] = df.Month.apply(lambda month: convert_to_qtr(month)). This is saying: look at the month column, df.Month. Then, call the convert_to_qtr function on each value in the month column. The result is then stored as a new column in your dataframe, Quarter.
you can use a map function in pandas. You need a dictionary that maps the months into quarters.
import pandas as pd
# an sorted list of months
list_of_months =['Jan','Feb','Mar','Apr','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
# creating a dictionary with the months and quarters
d = {}
for i, month in enumerate(list_of_months):
d[month] = 'Q' + str(i//3+1)
# example dataframe
df = pd.DataFrame(['Jan','Dec','Mar'],columns=['Month'])
# applying map to series
df['Month'].map(d)
The result looks like:
Month Quarter
0 Jan Q1
1 Dec Q4
2 Mar Q1

Get the season when entering a month and day (python)

I am writing a code that allows the user to enter a month and date and the program will tell them what season it will be given the information that the user entered. What I currently have working is that when you enter certain months that have the season in all their days it will display the season. But when I enter a month and date that has 2 seasons it gives me an error. This is the season guide that I am following:
Spring: March 20 - June 20
Summer: June 21 - September 21
Autumn: September 22 - December 20
Winter: December 21 - March 19
What I am trying to figure out is why the program is not printing out stuff when certain dates are entered. For example if I enter March 25th it should print out spring but it doesnt.
This is my code:
input_month = input('Enter a month: ')
input_day = input('Enter a date: ')
month_lower = input_month.lower()
seasons = ()
if month_lower == 'january' or month_lower == 'febuary' or month_lower == 'march' and input_day <19:
seasons = 'winter'
elif month_lower == 'march' and input_day <=19 or month_lower == 'april' or month_lower == 'may' or month_lower == 'june' and input_day < 21:
seasons = 'spring'
elif month_lower == 'july' or month_lower == 'august' or month_lower == 'september' and input_day <22:
seasons = 'summer'
elif month_lower == 'october' or month_lower == 'november' or month_lower == 'december' and input_day <20:
seasons = 'autumn'
else:
print('Please enter a valid date')
print(seasons)
You have a problem in the spring condition, you should check if the day is strictly superior to 19:
elif month_lower == 'march' and input_day > 19 or month_lower == 'april' or month_lower == 'may' or month_lower == 'june' and input_day < 21:
seasons = 'spring'
I supposed you're getting input not an int error when entering date since you compare input_day to an int, quick fix for this is to change all input_day to int(input_day).
But if your problem is that march 25 not printing out what you want but instead gave out please enter valid date then that'd be because you've not gave it a condition just yet, all above condition are average less than 20 but none talk about 22-30

My if statement is not returning what I think it should return [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 months ago.
def daysOfMonth():
month = input('Input the name of Month: ')
if month == 'January' or 'March' or 'May' or 'July' or 'August' or 'October' or 'December ':
print('No. of days: 31 days')
elif month == 'February':
print('No. of days: 28 days')
elif month == 'April' or "June" or 'September' or 'November':
print('No. of days: 30 days')
I Input April and it says 31 days

It works but why the need to alter the index by subtracting 1

Novice here, Question, why do I need to subtract one to reference the correct indice for month_name and ordinal.
This prints out a date, given year, month, and day as numbers from inputs.
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
+ ['st', 'nd', 'rd'] + 7 * ['th'] \
+ ['st']
year = input('Year: ')
month = input('Month (1-12: ')
day = input('Day (1-31): ')
month_number = int(month)
day_number = int(day)
month_name = months[month_number-1] #Although it works, what's the logic.
ordinal = day + endings[day_number-1 #Although it works, what's the logic.
print(month_name , ' ' + ordinal , ', ' + year)
Because python is zero-indexed. Which means the first element is 0 rather than 1
So for example:
In your code, March would be given by the user as 3 (1 Jan, 2 Feb, 3 March)
But in your python list, March would be at 2nd place (0 Jan, 1 Feb, 3 March)
Most of the coding languages are 0 indexed and for python everything that is iterable is 0 indexed as well
Simply because the Python index start from 0.
If you define a list as the following:
sample_list = ["Jan", "Feb", "Mar"]
print(sample_list[0])
You will get Jan printed instead of Feb.
Similarly, Feb 's index is 1 and Mar 's is 2.
Most programming languages have lists which are zero-indexed.
For example:
list = ["one", "two", "three"]
print(list[0]) # one
print(list[2]) # three

Why doesn't this project euler #19 code work? (Python)

I made a code for project euler's #19 problem in Python, and it doesn't give me the right answer.
The question is: You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
What is the problem here?:
months = {'January': 31,
'February': 28,
'March': 31,
'April': 30,
'May': 31,
'June': 30,
'July': 31,
'August': 31,
'September': 30,
'November': 30,
'December': 31
}
years = range(1900, 2001)
day = 1
def main():
global day
for year in years:
if year % 4 == 0 or year % 400 == 0:
months['February'] = 29
else:
months['February'] = 28
for month in months:
if months[month] == 31:
day += 31 % 7 +1
while day > 7:
day = day - 7
if day == 1:
yield day
result = sum(main())
print (result)
Also it generates different answers everytime I use,
Thanks :)
I don't understand the algorithm and your code. But I can say about this.
it generates different answers everytime I use
Probably you forgot to initialize month, year and day before executing result = sum(main()).
The solution will be simpler, if you use dateutil library:
In [16]: from datetime import datetime
In [17]: from dateutil.relativedelta import relativedelta
In [18]: current = datetime(1901, 1, 1)
In [19]: end = datetime(2001, 1, 1)
In [20]: ans = 0
In [21]: while current < end:
....: if current.weekday() == 6:
....: ans += 1
....: current += relativedelta(months=1)
....:
In [22]: ans
Out[22]: 171

Categories