[英]Formatting multiple lists into a table
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.
任何帮助、指示或提示都会很有用。
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
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.