以数据框格式打印列表

时间:2019-04-04 11:47:04

标签: python python-3.x pandas list

我正在尝试以pandas数据框格式打印二维列表。

将数据打印为熊猫数据框的结果

Pandas Data Frame

我的代码

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

============

打印结果

normal List

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))

您可以使用格式的值来获得最适合您的结果