For loop is not giving expected output using pandas DataFrame - python

I want to write a bill program where i want the cgst, sgst from the bill as output. All was going fine but i got stuck on a problem. I want separate names of product from the result of dataframe's output but i am getting only the name of only one product but the amount was sum of two...
Here's my code:
import pandas as pd
count = 0
num = int(input("Type number of items: "))
while count < num:
count += 1
print("-----------------------")
item = input("Enter Item Name: ")
SP = int(input("enter selling price of " + item + ": "))
gstrate = float(input("Enter GST rate: "))
cgst = SP * ((gstrate/2)/100)
sgst = cgst
amount = SP + cgst + sgst
data = pd.DataFrame({
'Item ': [item],
'Price': [SP],
'CGST': [cgst],
'SGST': [sgst],
'Amount payable': [amount],
})
print(data)
what i am getting is this example output:
Type number of items: 2
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 2341
Enter GST rate: 34
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1234567
Enter GST rate: 15
Item Price CGST SGST Amount payable
0 iphone 1234567 92592.525 92592.525 1419752.05
```
What i want the output to be:
Type number of items: 2
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1000
Enter GST rate: 18
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 1000
Enter GST rate: 18
Item Price CGST SGST Amount payable
0 iphone 1000 90.0 90.0 1180.0
1 samsung 1000 90.0 90.0 1180.0
As you can see, i am getting only name samsung not iphone and samsung saparatley

In each iteration of your loop you are creating a new data frame with only this loops data and overwitting any data that was in the last data frame. So when you finish your loops and print the dataframe all thats in it is the data from the last iteration of the loop since you created a new dataframe on each iteration.
Instead you could create the data frame before the loop and then just append to the data frame on each iteration of the loop
import pandas as pd
items = []
columns = ['Item', 'Price', 'CGST', 'SGST', 'Amount payable']
df = pd.DataFrame(columns=columns)
num = int(input("Type number of items: "))
for _ in range(num):
print("-----------------------")
item = input("Enter Item Name: ")
SP = int(input("enter selling price of " + item + ": "))
gstrate = float(input("Enter GST rate: "))
cgst = SP * ((gstrate/2)/100)
sgst = cgst
amount = SP + cgst + sgst
data = [item, SP, cgst, sgst, amount]
df_row = dict(zip(columns, data))
df = df.append(df_row, ignore_index=True)
print(df)
OUTPUT
Type number of items: 2
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1000
Enter GST rate: 18
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 1000
Enter GST rate: 18
Item Price CGST SGST Amount payable
0 iphone 1000 90.0 90.0 1180.0
1 samsung 1000 90.0 90.0 1180.0

Related

Sum of values in a multiple lists of a dict

I am new to python and have been trying to add values that I get from iterating over a list of dictionaries.
I keep running into 'builtin_function_or_method' object is not iterable' error message or unsupported type. Any help would be much appreciated.
here is my code:
def inventory(acct_info, months_subscribed, add_free_months, video_on_demand):
print(acct_info)
for info in acct_info:
print('-')
if info.get('months_subscribed') == 3:
months_subscribed_total = info.get('months_subscribed') * 18
elif info.get('months_subscribed') < 3:
months_subscribed_total = info['months_subscribed'] * 7
elif info.get('months_subscribed') > 3:
months_subscribed_total = info['months_subscribed'] - 3 * 7 + 18
print(f"User {info.get('name')} has months subscribed total of : $ {months_subscribed_total} ")
if info['ad_free_months'] > 0:
ad_free_total = info.get('ad_free_months') * 2
print(f" User {info.get('name')} total ad free is : {ad_free_total} ")
if info['video_on_demand'] > 0:
video_on_demand_total = info.get('video_on_demand') * 27.99
print(f" User {info.get('name')} total video on demand is : {video_on_demand_total} ")
acct_all_total = int(months_subscribed_total + ad_free_total + video_on_demand_total)
acct_all_total = [int(acct_all_total)]
print(f"Total for {info.get('name')} is: {acct_all_total} ")
acct_info = [{'name': 'acct_1', 'months_subscribed' : 2 , 'ad_free_months' : 3 , 'video_on_demand' : 1} ,
{'name': 'acct_2', 'months_subscribed' : 1 , 'ad_free_months' : 2 , 'video_on_demand' : 2},
{'name': 'acct_3', 'months_subscribed' : 2 , 'ad_free_months' : 1 , 'video_on_demand' : 3}]
combined_total = 0
months_subscribed = 0
ad_free_months = 0
video_on_demand = 0
months_subscribed_total = 0
ad_free_total = 0
video_on_demand_total = 0
inventory(acct_info, months_subscribed, ad_free_months, video_on_demand)
acct_all_total = 0
main()
Output so far is :
User acct_1 has months subscribed total of : $ 14
User acct_1 total ad free is : 6
User acct_1 total video on demand is : 27.99
Total for acct_1 is: [47]
-
User acct_2 has months subscribed total of : $ 7
User acct_2 total ad free is : 4
User acct_2 total video on demand is : 55.98
Total for acct_2 is: [66]
-
User acct_3 has months subscribed total of : $ 14
User acct_3 total ad free is : 2
User acct_3 total video on demand is : 83.97
Total for acct_3 is: [99]
What i am trying to sum up is the total for all of the users. I manage to get a total for each user, but i then want add the totals of that. Thank you.
You can take into consideration modifying your code a little bit your code.
I would move out the for loop from your function to make it do just one thing: do the inventory for a given account.
The following code is just an example, but it provides an alternative solution for your question.
def inventory(info, months_subscribed, add_free_months, video_on_demand):
acct_all_total = 0 # here you init the total value to 0
if info.get('months_subscribed') == 3:
months_subscribed_total = info.get('months_subscribed') * 18
elif info.get('months_subscribed') < 3:
months_subscribed_total = info['months_subscribed'] * 7
elif info.get('months_subscribed') > 3:
months_subscribed_total = info['months_subscribed'] - 3 * 7 + 18
print(f"User {info.get('name')} has months subscribed total of : $ {months_subscribed_total} ")
if info['ad_free_months'] > 0:
ad_free_total = info.get('ad_free_months') * 2
print(f" User {info.get('name')} total ad free is : {ad_free_total} ")
if info['video_on_demand'] > 0:
video_on_demand_total = info.get('video_on_demand') * 27.99
print(f" User {info.get('name')} total video on demand is : {video_on_demand_total} ")
acct_all_total = int(months_subscribed_total + ad_free_total + video_on_demand_total)
# acct_all_total = [int(acct_all_total)]
print(f"Total for {info.get('name')} is: {acct_all_total} ")
return acct_all_total
Please note I also commented the # acct_all_total = [int(acct_all_total)]
Then you can call it
acct_info = [{'name': 'acct_1', 'months_subscribed': 2, 'ad_free_months': 3, 'video_on_demand': 1},
{'name': 'acct_2', 'months_subscribed': 1, 'ad_free_months': 2, 'video_on_demand': 2},
{'name': 'acct_3', 'months_subscribed': 2, 'ad_free_months': 1, 'video_on_demand': 3}]
combined_total = 0
months_subscribed = 0
ad_free_months = 0
video_on_demand = 0
months_subscribed_total = 0
ad_free_total = 0
video_on_demand_total = 0
acct_all_total = 0
for acct in acct_info:
acct_all_total+=inventory(acct, months_subscribed, ad_free_months, video_on_demand)
print("Tot:",acct_all_total)
Output:
User acct_1 has months subscribed total of : $ 14
User acct_1 total ad free is : 6
User acct_1 total video on demand is : 27.99
Total for acct_1 is: 47
User acct_2 has months subscribed total of : $ 7
User acct_2 total ad free is : 4
User acct_2 total video on demand is : 55.98
Total for acct_2 is: 66
User acct_3 has months subscribed total of : $ 14
User acct_3 total ad free is : 2
User acct_3 total video on demand is : 83.97
Total for acct_3 is: 99
Tot: 212
Edited to reflect comments.
If you want to get the largest of your total, you have to change the code a bit. Consider to use the built-in function max() https://docs.python.org/3.8/library/functions.html#max and sum() https://docs.python.org/3.8/library/functions.html#sum.
max() returns the largest item in an iterable or the largest of two or more arguments. sum() sums all the element in an iterable. So, let's use an iterable in our code
tot = list()
for acct in acct_info:
# here, we gonna append each total
tot.append(inventory(acct, months_subscribed, ad_free_months, video_on_demand))
print("all the values:",tot)
print("the largest is:",max(tot)) # here we extract the largest item of the list
print("Total:",sum(tot)) # here we sum all the element of the list tot
Output:
all the values: [47, 66, 99]
the largest is: 99
Total: 212
I modified your inventory function, now it contains a list before the loop start and it holds all the totals of the users that you are printing at the bottom of the loop, at the end using the sum function the grand total of all users can be calculated
def inventory(acct_info, months_subscribed, add_free_months, video_on_demand):
print(acct_info)
all_users_collection = []
for info in acct_info:
print('-')
if info.get('months_subscribed') == 3:
months_subscribed_total = info.get('months_subscribed') * 18
elif info.get('months_subscribed') < 3:
months_subscribed_total = info['months_subscribed'] * 7
elif info.get('months_subscribed') > 3:
months_subscribed_total = info['months_subscribed'] - 3 * 7 + 18
print(f"User {info.get('name')} has months subscribed total of : $ {months_subscribed_total} ")
if info['ad_free_months'] > 0:
ad_free_total = info.get('ad_free_months') * 2
print(f" User {info.get('name')} total ad free is : {ad_free_total} ")
if info['video_on_demand'] > 0:
video_on_demand_total = info.get('video_on_demand') * 27.99
print(f" User {info.get('name')} total video on demand is : {video_on_demand_total} ")
acct_all_total = int(months_subscribed_total + ad_free_total + video_on_demand_total)
acct_all_total = [int(acct_all_total)]
all_users_collection.append(int(acct_all_total))
print(f"Total for {info.get('name')} is: {acct_all_total} ")
acct_info = [{'name': 'acct_1', 'months_subscribed' : 2 , 'ad_free_months' : 3 , 'video_on_demand' : 1} ,
{'name': 'acct_2', 'months_subscribed' : 1 , 'ad_free_months' : 2 , 'video_on_demand' : 2},
{'name': 'acct_3', 'months_subscribed' : 2 , 'ad_free_months' : 1 , 'video_on_demand' : 3}]
combined_total = 0
months_subscribed = 0
ad_free_months = 0
video_on_demand = 0
months_subscribed_total = 0
ad_free_total = 0
video_on_demand_total = 0
inventory(acct_info, months_subscribed, ad_free_months, video_on_demand)
acct_all_total = 0
print('Total for all users is', sum(all_users_collection))
The other approach can be to use a single variable and increment for every total of a user at the end you will get total of all users

first python program, having trouble looping [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
Basically i want my output from previous value to be new input.
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
for month in range(24):
amount = (((deposit2 * RSK) * rate) * 30 + md + deposit2)
new_amount = amount
print("%4d%21.2f" % (month, new_amount ))
Current output:
Enter initial deposit: 55000
Risk: 0.38
Rate: 0.025
monthly deposits: 10000
0 80675.00
1 80675.00
2 80675.00
3 80675.00
4 80675.00
5 80675.00
6 80675.00
7 80675.00
8 80675.00
9 80675.00
10 80675.00
11 80675.00
12 80675.00
13 80675.00
14 80675.00
15 80675.00
16 80675.00
17 80675.00
18 80675.00
19 80675.00
20 80675.00
21 80675.00
22 80675.00
23 80675.00
Desired output:
Enter initial deposit: 55000
Risk: 0.38
Rate: 0.025
monthly deposits: 10000
0 80675.00
1 113667.00
2 156063.00
3 210540.00
I basically want each output value of input for next process. For example 80675 becomes the new deposit2 value.
Please help me in this
You simply need to reassign deposit2 to amount for every iteration of the loop. Changing the value of variables is a very common thing to do, and there's nothing wrong with doing it. Also, the variable new_amount is not needed, you can simply just change deposit2 to amount once it is calculated. Here's your code, but fixed:
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
for month in range(24):
amount = (((deposit2 * RSK) * rate) * 30 + md + deposit2)
deposit2 = amount
print("%4d%21.2f" % (month, deposit2 ))
Set a new "amount" variable equal to the user input (deposit2) to
start and then just update it in the loop.
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
amount = deposit2
for month in range(24):
amount = amount * RSK * rate * 30 + md + amount
print("%4d%21.2f" % (month, amount))

Program to enter 5 student mark across 4 subjects and output highest average mark of student and subject

I am trying to write a program where i need to be able to enter 5 student marks across 4 different subjects and then output the highest average mark of both the student and the subject.
The desired input and output is :
Student 1 (courses 1-4): 50 60 70 60
Student 2 (courses 1-4): 100 90 87 90
Student 3 (courses 1-4): 70 100 90 90
Student 4 (courses 1-4): 30 65 50 50
Student 5 (courses 1-4): 58 50 74 43
The highest average mark of students: 91.75
The highest average mark of courses: 74.2
The current code I have works for calculating for one subject and not 4. How am I able to enter 4 grades per student to get my desired output.
see my code below:
m1 = int(input("Student 1 (courses 1-4): "))
m2 = int(input("Student 2 (courses 1-4): "))
m3 = int(input("Student 3 (courses 1-4): "))
m4 = int(input("Student 4 (courses 1-4): "))
m5 = int(input("Student 5 (courses 1-4): "))
avg = (m1 + m2+ m3+ m4 + m5) / 5;
avg1 =(m1 + m2+ m3+ m4 + m5) / 20;
print("The Highest average mark of students =", avg)
print("The Highest average mark of courses =", avg1)
This code does the job,
import pandas as pd
import numpy as np
# Part 1
student_num = 5
all_marks = []
for i in range(student_num):
marks = input(f"Student {i + 1} (courses 1-4): ")
all_marks.append(list(map(float, marks.split(" "))))
# Part 2
df = pd.DataFrame(all_marks, columns = ['Marks'])
course_avg = df.Marks.apply(np.mean)
student_avg = df.Marks.apply(np.mean, axis = 1)
The first part of the code converts the input into numbers and stores them into a list. This list is then converted into a data frame in Part 2. I firstly apply np.mean on the columns to find the average for each course, then on the rows to find the average for each student.
You can use idxmax() on both course_avg and student_avg to find the index of the maximum average and find the course/student with the highest average accordingly.
(It's better to store the values in a .xlsx or .csv file directly instead of inputing them through Python this way. Once you have the files, just pass the file path in pd.read_excel() or pd.read_csv() depending upon the format of the file.)
First, create a dictionary to take the inputs of marks for each student. Lets call it d_marks. Create a dictionary to get the average of all students. Let's call it avg_marks. Create a dictionary to get the total marks of all courses. Let's call it avg_course. After that get the max of them. Here's how you can do it:
d_marks = {}
avg_marks = {}
avg_course = {}
for i in range(1,6): # We loop for 5 students
d_marks[f'Student {i} (courses 1-4)'] = list(map(int, input(f"Student {i} (courses 1-4): ").split())) # Split the string and creates an integer list
avg_marks[f'Average of Student {i}'] = sum(d_marks[f'Student {i} (courses 1-4)']) / len(d_marks[f'Student {i} (courses 1-4)']) #Create average dictionary for Students
for j in range(1, len(d_marks[f'Student {i} (courses 1-4)'])+1):
if f'Course {j} sum' in avg_course: # if course sum already in dictionary then add it to previous.
avg_course[f'Course {j} sum'] += d_marks[f'Student {i} (courses 1-4)'][j-1]
else:
avg_course[f'Course {j} sum'] = d_marks[f'Student {i} (courses 1-4)'][j-1] # if course sum not in dictionary then create one.
print("The Highest average mark of students =", max(avg_marks.values()))
print("The Highest average mark of courses =", max(avg_course.values())/ len(d_marks))
Output:
Student 1 (courses 1-4): 50 60 70 60
Student 2 (courses 1-4): 100 90 87 90
Student 3 (courses 1-4): 70 100 90 90
Student 4 (courses 1-4): 30 65 50 50
Student 5 (courses 1-4): 58 50 74 43
The Highest average mark of students = 91.75
The Highest average mark of courses = 74.2

how to sum values in a new column, based on conditions and occurrence of the same value in col (value recurrence) as a factor

I'm trying to find a way to update values in a new column having written a piece of code that in every step (row by row) displays the sum of buy/sell orders with the best price.
stock_buy_sell = {
"Id":[1, 2, 3, 4, 3, 5],
"Order":["Buy", "Sell", "Buy", "Buy", "Buy", "Sell"],
"Type":["Add", "Add", "Add", "Add", "Remove", "Add"],
"Price":[21.0, 25.0, 23.0, 23.0, 23.0, 28],
"Quantity":[100, 200, 50, 70, 50, 100]}
Id Order Type Price Quantity
0 1 Buy Add 21.0 100
1 2 Sell Add 25.0 200
2 3 Buy Add 23.0 50
3 4 Buy Add 23.0 70
4 3 Buy Remove 23.0 50
5 5 Sell Add 28.0 100
Because of updates that may occur for a particular id, I need to find a way to use this factor to proper populate new columns: Sum of income and Stock quantity.
Id Order Type Price Quantity Sum Of Income Stock Quantity Total Profit
0 1 Buy Add 21.0 100 0 0 0
1 2 Sell Add 25.0 200 0 0 0
2 3 Buy Add 23.0 50 0 0 0
3 4 Buy Add 23.0 70 0 0 0
4 3 Buy Remove 23.0 50 0 0 0
5 5 Sell Add 28.0 100 0 0 0
In this simple example, besides the fact that I need to compute Sum of income and Stock quantity based on buy/sell actions according to previous rows (row after row), the problem occurs in the 4th row where id: 3 should be based on the id in 2nd row. In other words, to properly populate Sum of income and Stock quantity I need to find a way to subtract price and quantity values based on a function that will be triggered when some id existed previously.
I try to find a way to do it with df.apply(), pd.series.apply(). I, also, looked at the possibility of implementing the pd.shift method. But, I can't figure out how to build the logic and with what method.
Expected output (I count it manually):
Id Order Type Price Quantity Sum of Income Stock Quantity Total Profit
1 1 Buy Add 21 100 -21 100 -2100
2 2 Sell Add 25 200 4 -100 5000
3 3 Buy Add 23 50 -19 -50 -1150
4 4 Buy Add 23 70 -42 20 -1610
5 3 Buy Remove 23 50 -19 -30 1150
6 5 Sell Add 28 100 9 -130 2800
====================================================================
The following part of my post is not directly relevant to the question, so it may be omitted by those answering.
The following part is a solution to the problem for a situation in which we get input as subsequent dictionary-type objects and - right away - we can build a complete database (the same as in the question).
In other words, at the beginning I have no data,
the shareholder performs a buy / sell action (first step), eg
apples_dct1 = {1: [" Buy "," Add ", 20.0, 100]}.
Then comes the next step:
apples_dct2 = {2: ["Sell", "Add", 25.0, 200]}
ect.
import pandas as pd
apples_dct1 = {1:["Buy", "Add", 21.0, 100]}
apples_dct2 = {2:["Sell", "Add", 25.0, 200]}
apples_dct3 = {3:["Buy", "Add", 23.0, 50]}
apples_dct4 = {4:["Buy", "Add", 23.0, 70]}
apples_dct5 = {3:["Buy", "Remove", 23.0, 50]}
apples_dct6 = {5:["Sell", "Add", 28.0, 100]}
engine_dict = {}
def magic_engine(dict_apples):
"""
creating objects from dict_apples:
"""
dict_key = list(dict_apples.keys())[0]
order = dict_apples[dict_key][0]
type_buy_sell = dict_apples[dict_key][1]
price = dict_apples[dict_key][2]
quantity = dict_apples[dict_key][3]
# print(dict_key)
# print("dict_key[1] ", dict_apples[dict_key][1]) # test
"""
First instance of data in a new dict `engine_dict`:
"""
if (bool(engine_dict) == False and
dict_apples[dict_key][1] == "Add" and
dict_apples[dict_key][0] == "Buy"):
sum_of_income_extend = -price
stock_quantity_extended = quantity
profit_extended = -(price * quantity)
base_list = [
order,
type_buy_sell,
price,
quantity,
sum_of_income_extend,
stock_quantity_extended,
profit_extended
]
# print("base_list ", base_list)
engine_dict[dict_key] = base_list
# print(engine_dict) # Test
return engine_dict
elif (bool(engine_dict) == False and
dict_apples[dict_key][1] == "Add" and
dict_apples[dict_key][0] == "Sell"):
sum_of_income_extend = price
stock_quantity_extended = quantity
profit_extended = price * quantity
base_list = [
order, type_buy_sell,
price,
quantity,
sum_of_income_extend,
stock_quantity_extended,
profit_extended
]
# print("base_list ", base_list)
engine_dict[dict_key] = base_list
# print(engine_dict) # Test
return engine_dict
"""
Adding new key-value pairs to `engine_dict`
where
`update_sum_of_income_extend`,
`stock_quantity_extend`,
`profit_extended`
are based on the previous `engine_dict` key.
With that, we can update the income,
stock quantity and total profit for stock holder.
"""
if (bool(engine_dict) == True and
dict_apples[dict_key][1] == "Add" and
dict_apples[dict_key][0] == "Buy"):
update_sum_of_income_extend = (
engine_dict[list(engine_dict.keys())[-1]][4] - (price)
)
stock_quantity_extend = (
engine_dict[list(engine_dict.keys())[-1]][5] + quantity
)
profit_extended = -(price * quantity)
base_list = [
order,
type_buy_sell,
price,
quantity,
update_sum_of_income_extend,
stock_quantity_extend,
profit_extended
]
# print("base_list ", base_list)
engine_dict[dict_key] = base_list
# print(engine_dict) # Test
return engine_dict
elif (bool(engine_dict) == True and
dict_apples[dict_key][1] == "Add" and
dict_apples[dict_key][0] == "Sell"):
update_sum_of_income_extend = (
engine_dict[list(engine_dict.keys())[-1]][4] + (price)
)
stock_quantity_extend = (
engine_dict[list(engine_dict.keys())[-1]][5] - quantity
)
profit_extended = price * quantity
# print("engine_dict[list(engine_dict.keys())[-1]][2] ", engine_dict[list(engine_dict.keys())[-1]][2])
# print("price ", price)
base_list = [
order,
type_buy_sell,
price,
quantity,
update_sum_of_income_extend,
stock_quantity_extend,
profit_extended
]
engine_dict[dict_key] = base_list
return engine_dict
elif (bool(engine_dict) == True and
dict_apples[dict_key][1] == "Remove" and
dict_apples[dict_key][0] == "Buy"):
update_sum_of_income_extend = (
engine_dict[list(engine_dict.keys())[-1]][4] + (price)
)
stock_quantity_extend = (
engine_dict[list(engine_dict.keys())[-1]][5] - quantity
)
profit_extended = price * quantity
# print("engine_dict[list(engine_dict.keys())[-1]][2] ", engine_dict[list(engine_dict.keys())[-1]][2])
# print("price ", price)
base_list = [
order,
type_buy_sell,
price,
quantity,
update_sum_of_income_extend,
stock_quantity_extend,
profit_extended
]
"""
Because a dictionary can have just unique keys, for "removing action"
I create a new key build: key + instance number of action.
With that, it will be easy to find all removing actions (they will be floats)
If there would be more "removing action" instances, then I will have for example:
main key 3
first "removing action" with key 3.1
second "removing action" with key 3.2
third "removing action" with key 3.3
ect.
"""
for i in list(engine_dict.keys())[:]:
if i == dict_key:
dict_key = dict_key + 0.1
engine_dict[dict_key] = base_list
return engine_dict
"""
Below I have all the steps taken by the shareholder
"""
magic_engine(apples_dct1)
magic_engine(apples_dct2)
magic_engine(apples_dct3)
magic_engine(apples_dct4)
magic_engine(apples_dct5)
magic_engine(apples_dct6)
"""
Based on a dictionary that includes all shareholder activities,
I am building a dataframe in Pandas:
"""
df_col = [
'Order',
'Type',
'Price',
'Quantity',
'Sum of income',
'Stock quantity',
'total profit'
]
new_table_buy_sell = pd.DataFrame(engine_dict)
final_table = new_table_buy_sell.transpose()
final_table.set_index([pd.Index([1,2,3,4,5,6]), list(engine_dict.keys())], inplace=True)
final_table.columns = df_col
final_table.columns = final_table.columns.rename("id")
final_table
Output:
Id Order Type Price Quantity Sum Of Income Stock Quantity Total Profit
1 1.0 Buy Add 21 100 -21 100 -2100
2 2.0 Sell Add 25 200 4 -100 5000
3 3.0 Buy Add 23 50 -19 -50 -1150
4 4.0 Buy Add 23 70 -42 20 -1610
5 3.1 Buy Remove 23 50 -19 -30 1150
6 5.0 Sell Add 28 100 9 -130 2800
We could use a mapping dictionary to use "Order" and "Type" as calculating the cumulative price and quantity (which we calculate using cumsum). Finally, assign the "Total" column by multiplying the "Quantity" by the cumulative price (which is renamed "Sum of income"):
order_mapping = {'Buy': 1, 'Sell': -1}
type_mapping = {'Add': 1, 'Remove': -1}
df = (df.join(df[['Price','Quantity']]
.mul(df['Order'].map(order_mapping) * df['Type'].map(type_mapping), axis=0)
.assign(Price=lambda x: -x['Price'])
.cumsum()
.rename(columns={'Price':'Sum of income', 'Quantity':'Stock quantity'}))
.assign(Total=lambda x: x['Quantity']*x['Price']))
Output:
Id Order Type Price Quantity Sum of income Stock quantity Total
0 1 Buy Add 21.0 100 -21.0 100 -2100.0
1 2 Sell Add 25.0 200 4.0 -100 5000.0
2 3 Buy Add 23.0 50 -19.0 -50 1150.0
3 4 Buy Add 23.0 70 -42.0 20 1610.0
4 3 Buy Remove 23.0 50 -19.0 -30 1150.0
5 5 Sell Add 28.0 100 9.0 -130 2800.0
The general idea is that we want to use the "Order" column to determine whether we want to add or subtract values as we find the cumulative sums of "Price" and "Quantity". That's what we're doing with map + mul. Then after we find the cumulative sums of these columns (note that cumulative sum works on a particular column), we find the total by multiplying two columns (this uses two columns).

How to sum specific integer values of Python List

I'm trying to sum integer values from the list using sum function. Unfortunately, it is adding all the values of the list but not those which I need from the user.
Here is my code:
tourist_attractions = []
distance = []
entry_cost = []
for i in range(3):
tourist_attractions.append (input("Enter Tourist place: "))
tourist_distance =(int(input("Enter distance: ")))
if tourist_distance > 50:
print("Invalid Entry")
continue
if tourist_distance <= 50:
distance.append(tourist_distance)
cost = (float(input("Enter cost: ")))
if cost > 100:
print("cost must be between 1-100")
continue
if cost > 0 or cost <= 100:
entry_cost.append(cost)
print()
for line in tourist_attractions:
print("Place:", line)
for line in distance:
print("Distance:", line)
for line in entry_cost:
print("Cost:", line)
print()
number_of_places_to_visit = int(input("Total number of places to visit: "))
x = 1
while x <= number_of_places_to_visit:
select_tourist_place = input("select tourist place, 0-3: ")
x = x + 1
if select_tourist_place == "0":
print(tourist_attractions[0], distance[0], entry_cost[0])
elif select_tourist_place == "1":
print(tourist_attractions[1], distance[1], entry_cost[1])
elif select_tourist_place == "2":
print(tourist_attractions[2], distance[2], entry_cost[2])
elif select_tourist_place == "3":
print(tourist_attractions[3], distance[3], entry_cost[3])
elif select_tourist_place == "4":
print(tourist_attractions[4], distance[4], entry_cost[4])
print("total cost: " , sum(entry_cost))
Result I am getting:
Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20
Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0
Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost: 50.0
>>>
I can understand, at the moment it is summing up all the appended list of entry_cost and giving me the total of 50 which should be 15 from London and 15 from Manchester. Any help?
print("total cost: " , sum(entry_cost))
definitely states your are iterating over ALL entry costs. You would want to store the selected indices and sum over the entries of those indices.

Categories