I need to format four separate lists (not nested) that look like this:
header = ["Product:" ,"Price:" ,"Quantity:"]
productList = ["apple" ,"banana" ,"cake"]
productPrice = [3.50 ,6.82 ,23.00]
productQty = [134 ,52 ,5]
into a table that looks like this:
Product: Price: Quantity
Apple $3.50 134
Banana $6.82 52
Cake $23.00 5
I want this table to update with the original source lists. I know I will need to execute this with some sort of loop. So for example if I was to update the lists:
header = ["Product:" ,"Price:" ,"Quantity:"]
productList = ["apple" ,"banana" ,"cake" ,"newItem1"]
productPrice = [3.50 ,6.82 ,23.00 ,00.00]
productQty = [134 ,52 ,5 ,100]
the table would now look like:
Product: Price: Quantity
Apple $3.50 134
Banana $6.82 52
Cake $23.00 5
newItem1 $00.00 100
Any ideas? Any help, pointers, or tips would be useful.
CodePudding user response:
You can use pandas
import pandas as pd
header = ["Product:", "Price:", "Quantity:"]
productList = ["apple", "banana", "cake", "newItem1"]
productPrice = [3.50, 6.82, 23.00, 00.00]
productQty = [134, 52, 5, 100]
df = pd.DataFrame({header[0]: productList, header[1]: [f'${p:.2f}' for p in productPrice], header[2]: productQty})
print(df)
Prints:
Product: Price: Quantity:
0 apple $3.50 134
1 banana $6.82 52
2 cake $23.00 5
3 newItem1 $0.00 100
CodePudding user response:
# convert below table into a format shown
header = ["Product:" ,"Price:" ,"Quantity:"]
productList = ["apple" ,"banana" ,"cake"]
productPrice = [3.50 ,6.82 ,23.00]
productQty = [134 ,52 ,5]
# make table from header, productList, productPrice, productQty
# convert table into a format shown below
'''
Product: Price: Quantity
Apple $3.50 134
Banana $6.82 52
Cake $23.00 5
newItem1 $00.00 100
'''
# make table from header, productList, productPrice, productQty
table=[]
table.append(header)
for i in range(len(productList)):
table.append([productList[i],productPrice[i],productQty[i]])
#use dataframes, make productlist as index, headers as columns
import pandas as pd
df=pd.DataFrame(table[1:],columns=table[0])
print(df)