If else if statement in libre office - if-statement

I am using libre office and I am trying to apply If else if statement but I couldn't do that.
I have numbers with multiple conditions. In column "E" I have numbers. I want separate messages for separate numbers
For number- 0.00 = "standard 5,60 Euro charge"
For number- 5,60 = "standard 5,60 Euro charge"
For number- 8,00 = "standard 5,60 Euro charge"
For number- 10,95 = "Standard 14,95 Euro charge"
For number- 24,95 = "express 29,95 Euro charge"
for number- 30,00 = "Super 45,00 Euro charge"
=IF(E3<="8";"standardpaket 5,6 euro netto" ;elseif(E3="10.95";"DHL Sperrgut 14,95 Euro netto";elseif(E3="24.95";"DHL Express 29,95 Euro netto";else;"Free")))
I have tried with this but it doesn't work. I want messages in column "H".

I think it's been a long time, but since there's no conclusive answer I'll post an answer.
The VLOOKUP() solution is good if you need to choose between ranges.
For fixed values use a custom function.
Function SEL(byVall as String) as String
Select Case byVall
Case 0 : SEL = "standard 5,60 Euro charge"
Case 5.6 : SEL = "standard 5,60 Euro charge"
Case 8 : SEL = "standard 5,60 Euro charge"
Case 10.95 : SEL = "standard 14,95 Euro charge"
Case 24.95 : SEL = "Express 29,95 Euro charge"
Case 30 : SEL = "Super 45,00 Euro charge"
Case Else : SEL = "Free"
End Select
End Function

Related

Add a flag on the values of rows

I have a table (Student_classification) with two columns, Student Number and Subject (example):
Student Number Subject
122 Biology_Physics
122 Math
122 Music
125 music
125 geography
298 Math
298 Economics
My task is to get a new table where:
if the student Number has Biology_Physics and (either Math or Music or geography or economics) as Science
if the student number has (geography or music) and do not have any other as Humnity/arts
if the student has (Math or Economics) and do not have any other as EconomicsEngineering
My final result should be:
Student Number Type
122 Science
125 Humanity/arts
298 EconomicsEngineering
However, I get following table which is incorrect:
Student_Number Type
122 Other
122 EconomicEngineering
122 Humanity/arts
125 Humanity/arts
298 EconomicEngineering
I have written the following code in SAS, but the logics seems incorrect:
Proc Sql;
create table student_classification as
(
select distinct cust_num,
case
when Subject ='Biology_Physics' and Subject in ('Math' 'Music' 'geography' 'economics') then 'Science'
When Subject in ('geography' 'music') and Subject not in ('Biology_Physics' 'Math' 'economics') then 'Humanity/arts'
When Subject in ('math' 'economics) and subject not in ('Biology_Physics' 'Geography' 'Music') then 'EconomicEngineering'
else 'Other'
end as Type
from Student_classification
Group by student_number, Type
);
quit;
My use case is different, but simulating the similar idea here.
You try to compare values from multiple rows, thus you need conditional aggregation.
select cust_num,
case
-- has Biology_Physics and (either Math or Music or geography or economics) as Science
when max(case when Subject ='Biology_Physics' then 1 end) = 1
and max(case when Subject in ('Math', 'Music', 'geography', 'economics') then 1 end) = 1
then 'Science'
-- has (geography or music) and do not have any other as Humnity/arts
When max(case when Subject in ('geography', 'music') then 0 else 1 end) = 0
then 'Humanity/arts'
-- has (Math or Economics) and do not have any other as EconomicsEngineering
When max(case when Subject in ('math', 'economics) then 0 else 1 end) = 0
then 'EconomicEngineering'
else 'Other'
end as Type
from Student_classification
Group by cust_num

Why I get this output by print %f - Python 2.7

quick question: why do I get a lot of zeros after the decimal point in the output of this script (value of "total" variable)? (I know how to deal with it and get specific outbut by walk-arounds, but I'm curious why thi iutput looks like this)
Script:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
print
total = 0
for iteration in prices:
total = total+ prices[iteration] * stock[iteration]
print "total price: %f"%total
output:
banana
price: 4
stock: 6
apple
price: 2
stock: 0
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
total price: 117.000000 #********* why so many zeros?
Because that's the default number of decimal places for the %f formatter.
Add a precision specifier; for example, if you only want to display 2 decimal places, use %.2f:
print "total price: %.2f" % total
and the last line of output then becomes
total price: 117.00
The . followed by a digit in the format specification signals the precision specifier. See the String Formatting Operations documentation:
A conversion specifier contains two or more characters and has the following components, which must occur in this order:
[...]
Precision (optional), given as a '.' (dot) followed by the precision. [...]
Further on in the same documentation, the default for f is documented under footnote #3:
The precision determines the number of digits after the decimal point and defaults to 6.
you must replace %f by %d or by %i if you dont want zeros and if you want 1 zero you can replace it by %s:
>>> print "total price: %d"%total
total price: 117
>>> print "total price: %s"%total
total price: 117.0
>>> print "total price: %f"%total # Like you did
total price: 117.000000

How to delete words from a dataframe column that are present in dictionary in Pandas

An extension to :
Removing list of words from a string
I have following dataframe and I want to delete frequently occuring words from df.name column:
df :
name
Bill Hayden
Rock Clinton
Bill Gates
Vishal James
James Cameroon
Micky James
Michael Clark
Tony Waugh
Tom Clark
Tom Bill
Avinash Clinton
Shreyas Clinton
Ramesh Clinton
Adam Clark
I'm creating a new dataframe with words and their frequency with following code :
df = pd.DataFrame(data.name.str.split(expand=True).stack().value_counts())
df.reset_index(level=0, inplace=True)
df.columns = ['word', 'freq']
df = df[df['freq'] >= 3]
which will result in
df2 :
word freq
Clinton 4
Bill 3
James 3
Clark 3
Then I'm converting it into a dictionary with following code snippet :
d = dict(zip(df['word'], df['freq']))
Now if I've to remove words from df.name that are in d(which is dictionary, with word : freq), I'm using following code snippet :
def check_thresh_word(merc,d):
m = merc.split(' ')
for i in range(len(m)):
if m[i] in d.keys():
return False
else:
return True
def rm_freq_occurences(merc,d):
if check_thresh_word(merc,d) == False:
nwords = merc.split(' ')
rwords = [word for word in nwords if word not in d.keys()]
m = ' '.join(rwords)
else:
m=merc
return m
df['new_name'] = df['name'].apply(lambda x: rm_freq_occurences(x,d))
But in actual my dataframe(df) contains nearly 240k rows and i've to use threshold(thresh=3 in above sample) greater than 100.
So above code takes lots of time to run because of complex search.
Is there any effiecient way to make it faster??
Following is a desired output :
name
Hayden
Rock
Gates
Vishal
Cameroon
Micky
Michael
Tony Waugh
Tom
Tommy
Avinash
Shreyas
Ramesh
Adam
Thanks in advance!!!!!!!
Use replace by regex created by joined all values of column word, last strip traling whitespaces:
data.name = data.name.replace('|'.join(df['word']), '', regex=True).str.strip()
Another solution is add \s* for select zero or more whitespaces:
pat = '|'.join(['\s*{}\s*'.format(x) for x in df['word']])
print (pat)
\s*Clinton\s*|\s*James\s*|\s*Bill\s*|\s*Clark\s*
data.name = data.name.replace(pat, '', regex=True)
print (data)
name
0 Hayden
1 Rock
2 Gates
3 Vishal
4 Cameroon
5 Micky
6 Michael
7 Tony Waugh
8 Tom
9 Tom
10 Avinash
11 Shreyas
12 Ramesh
13 Adam

Python 2.7x: How do I convert int of lets say 4.5 to 4.50

I am new (like 2 weeks) trying to learn Python 2.7x.
I am trying to do a basic program that has a user input a cost of a meal and it outputs how much it would be with a .15 tip. I want the output to look like 23.44 (showing 2 decimals)
My code:
MealPrice = float(raw_input("Please type in your bill amount: "))
tip = float(MealPrice * 0.15,)
totalPrice = MealPrice+tip
int(totalPrice)
print "Your tip would be: ",tip
print "Yout total bill would be: ",totalPrice
my output:
Please type in your bill amount: 22.22
Your tip would be: 3.333
Yout total bill would be: 25.553
You want to format your float value for printing only; use formatting:
print "Your tip would be: {:.2f}".format(tip)
print "Your total bill would be: {:.2f}".format(totalPrice)
The .2f is a formatting mini language specification for a floating point value of 2 digits after the decimal.
You need to remove the int() call to preserve those digits after the decimal. You don't need to call float() so much either:
MealPrice = float(raw_input("Please type in your bill amount: "))
tip = MealPrice * 0.15
totalPrice = MealPrice + tip
print "Your tip would be: {:.2f}".format(tip)
print "Your total bill would be: {:.2f}".format(totalPrice)
Demo:
Please type in your bill amount: 42.50
Your tip would be: 6.38
Your total bill would be: 48.88
You can further tweak the formatting to align those numbers up along the decimal point too.

How do I take already calculated totals that are in a loop and add them together?

I created this program in Python 2.7.3
I did this in my Computer Science class. He assigned it in two parts. For the first part we had to create a program to calculate a monthly cell phone bill for five customers. The user inputs the number of texts, minutes, and data used. Additionaly, there are overage fees. $10 for every GB of data over the limit, $.4, per minute over the limit, and $.2 per text sent over the limit. 500 is the limit amount of text messages, 750 is the limit amount of minutes, and 2 GB is the limit amount of data for the plan.
For part 2 of the assignment. I have to calculate the total tax collected, total charges (each customer bill added together), total goverment fees collected, total customers who had overages etc.
Right now all I want help on is adding the customer bills all together. As I said earlier, when you run the program it prints the Total bill for 5 customers. I don't know how to assign those seperate totals to a variable, add them together, and then eventually print them as one big variable.
TotalBill = 0
monthly_charge = 69.99
data_plan = 30
minute = 0
tax = 1.08
govfees = 9.12
Finaltext = 0
Finalminute = 0
Finaldata = 0
Finaltax = 0
TotalCust_ovrtext = 0
TotalCust_ovrminute = 0
TotalCust_ovrdata = 0
TotalCharges = 0
for i in range (1,6):
print "Calculate your cell phone bill for this month"
text = input ("Enter texts sent/received ")
minute = input ("Enter minute's used ")
data = input ("Enter Data used ")
if data > 2:
data = (data-2)*10
TotalCust_ovrdata = TotalCust_ovrdata + 1
elif data <=2:
data = 0
if minute > 750:
minute = (minute-750)*.4
TotalCust_ovrminute = TotalCust_ovrminute + 1
elif minute <=750:
minute = 0
if text > 500:
text = (text-500)*.2
TotalCust_ovrtext = TotalCust_ovrtext + 1
elif text <=500:
text = 0
TotalBill = ((monthly_charge + data_plan + text + minute + data) * (tax)) + govfees
print ("Your Total Bill is... " + str(round(TotalBill,2)))
print "The toatal number of Customer's who went over their minute's usage limit is... " ,TotalCust_ovrminute
print "The total number of Customer's who went over their texting limit is... " ,TotalCust_ovrtext
print "The total number of Customer's who went over their data limit is... " ,TotalCust_ovrdata
Some of the variables created are not used in the program. Please overlook them.
As Preet suggested.
create another variable like TotalBill i.e.
AccumulatedBill = 0
Then at the end of your loop put.
AccumulatedBill += TotalBill
This will add each TotalBill to Accumulated. Then simply print out the result at the end.
print "Total for all customers is: %s" %(AccumulatedBill)
Note: you don't normally use uppercase on variables for the first letter of the word. Use either camelCase or underscore_separated.