我正在尝试以pandas数据框格式打印二维列表。
将数据打印为熊猫数据框的结果
我的代码
cols = ["prod_id", "description", "cost"]
data = [["p01", "Domaxx Geniune Leather RFID Blocking Trifold Wallets-Made Genuine Soft Leather Large Classic Pocket Wallet,Holding 9 Cards Photo ID Coin Pocket and 2 Note compartments-Black Surface/Orange Inner", "10.00"],
["p02","Neck Wallet, Passport Holder with RFID Blocking Anti-Theft Travel Pouch Security Wallet for Credit Cards and Passport - Silver","15.00"]]
temp_str = ''
for item in cols :
temp_str += "\t " + item
print(temp_str)
i = 0
for row in data :
print(str(i) + "\t" + row[0] + "\t" + row[1] + "\t" + row[2])
i += 1
============
答案 0 :(得分:0)
我不确定我是否理解您的输入,但是您是否想要这样:
prod_id description cost
0 p01 Domaxx Geniune Leather RFID Blocking Trifold W... 10.00
1 p02 Neck Wallet, Passport Holder with RFID Blockin... 15.00
来自:
cols = ["prod_id", "description", "cost"]
data = [["p01", "Domaxx Geniune Leather RFID Blocking Trifold Wallets-Made Genuine Soft Leather Large Classic Pocket Wallet,Holding 9 Cards Photo ID Coin Pocket and 2 Note compartments-Black Surface/Orange Inner", "10.00"], ["p02","Neck Wallet, Passport Holder with RFID Blocking Anti-Theft Travel Pouch Security Wallet for Credit Cards and Passport - Silver","15.00"]]
只需执行以下操作:
import pandas as pd
df = pd.DataFrame(data, columns=cols)
我为您展示了一个具有较短列字段的示例:
data = [["p01", "Domaxx Geniune Leather RFID Blocking Trifold Wallets-Made", "10.00"],
["p02","Neck Wallet, Passport Holder with RFID Blocking Anti-Theft Travel Pouch Security Wallet f","15.00"]]
fmt = '{:<4}{:<10}{:<100}{}'
data1 = map(list, zip(*data))
print(fmt.format('', "prod_id", "description", "cost")) # your columns here
for i, (x, y, z) in enumerate(zip(data1[0], data1[1], data1[2])):
print(fmt.format(i, x, y, z))
您可以使用格式的值来获得最适合您的结果