使用Python将列名与CSV文件中的数据对齐
这是我用来将数据写入.csv文件的代码使用Python将列名与CSV文件中的数据对齐,python,csv,Python,Csv,这是我用来将数据写入.csv文件的代码 with open('temp.csv', 'a') as fp: a = csv.writer(fp, delimiter='\t') data = [['faceXpos','faceYpos','faceHeight','faceWidth','imageViewHeight','imageViewWidth','tshirtXpos', 'tshirtYpos','tshirtWidth','tshirtHeight
with open('temp.csv', 'a') as fp:
a = csv.writer(fp, delimiter='\t')
data = [['faceXpos','faceYpos','faceHeight','faceWidth','imageViewHeight','imageViewWidth','tshirtXpos', 'tshirtYpos','tshirtWidth','tshirtHeight'],
[faceXpos, faceYpos, faceHeight, faceWidth, imageViewHeight, imageViewWidth, tshirtXpos, tshirtYpos, tshirtWidth, tshirtHeight]]
a.writerows(data)
输出如下所示:
faceXpos faceYpos faceHeight faceWidth imageViewHeight imageViewWidth tshirtXpos tshirtYpos tshirtWidth tshirtHeight
118 432 84 84 568 320 13.0 136 294.0 346.0
faceXpos faceYpos faceHeight faceWidth imageViewHeight imageViewWidth tshirtXpos tshirtYpos tshirtWidth tshirtHeight
117.4 433.81 82.35999 82.36 568 320 14.45 134.19 288.26 340.09
如何对齐,使每列下的数据以更易于读取的方式完全对齐?期望输出:(即使数据位于列的中心也可以)
这有点棘手,因为CSV编写器不直接支持结构化和格式化输出。如果您编写自己的输出例程,这将是最简单的。 例如:
fp = open('temp.csv', 'a')
labelLine = list()
valueLine = list()
for label, value in zip(*data): # unzips the list, so each elements (label and value) get extracted pairwise
padding = max(len(str(label)), len(str(value))) # what is longer, the label or the value?
labelLine.append('{0:<{1}}'.format(label, padding)) # generate a string with the variable whitespace padding
valueLine.append('{0:<{1}}'.format(value, padding)) # generate a string with the variable whitespace padding
# now write everything to the file:
fp.write('\t'.join(labelLine) + '\n')
fp.write('\t'.join(valueLine) + '\n')
fp.close()
但是,您必须小心,因为现在您的数据仍然是分开的,但是您的CSV阅读器必须去掉多余的空白。您可以将'\t'.join替换为''.join,如果您同意使用纯空格分隔的话
我希望这有帮助:)
致意首先,您需要的是“固定宽度文件”,而不是CSV 有一个名为的模块可以帮助您:
from prettytable import PrettyTable
# Initialize the object passing the table headers
t = PrettyTable(['A', 'B', 'C'])
t.align='l'
t.border=False
t.add_row([111,222,333])
t.add_row([444,555,666])
t.add_row(['longer text',777,'even longer text here'])
print str(t)
输出:
A B C
111 222 333
444 555 666
longer text 777 even longer text here
因为已经有一段时间没有更新了,所以我想向它添加一个点头。我个人更喜欢这个,因为它与数据科学软件包配合得很好,因此您可以按照自己的意愿构建数据,并获得一个表表示,而无需太多麻烦
下面是一个例子:
data=numpy.array([1,2,3,4.],[5,6,7,8.],“这是一些looooong文本”。拆分(“”)].T
table=制表。制表(数据,tablefmt='fancy_grid',floatfmt='0.2E','0.4e','')
打印(表格)
╒══════════╤════════════╤═══════════════════╕
│ 1.00E+00│ 5.0000e+00│ 这是│
├──────────┼────────────┼───────────────────┤
│ 2.00E+00│ 6.0000e+00│ 一些│
├──────────┼────────────┼───────────────────┤
│ 3.00E+00│ 7.0000e+00│ 呜呜呜呜│
├──────────┼────────────┼───────────────────┤
│ 4.00E+00│ 8.0000e+00│ 正文│
╘══════════╧════════════╧═══════════════════╛
其中一个有:
dates=pandas.date\u范围('20180101',句点=4)
data=numpy.vstack([numpy.random.randn(4,4),numpy.array(“这里有一些looooong文本”).split(“”))].T
df=pandas.DataFrame(数据,索引=日期,列=列表('ABCD'))#索引列的第一列为空
df.index=df.index.strftime(“%Y-%m-%d”)
df.index.name='dates'
df=df.reindex(['B','D','A','C',轴=1)
#table=df.to_string()#默认字符串表示法
table=tablate.tablate(df,tablefmt='presto',headers=[df.index.name]+df.columns.tolist(),
floatfmt=['''0.4f','','0.2e'],numalign='right',stralign='center')
打印(表格)
日期| B | D | A | C
------------+---------+-------------------+---------------------+-----------
2018-01-01 | 0.8080 |这里是| 1.5430201221283801 | 8.81e-01
2018-01-02 |-1.0354 | some |-1.0642628831039138 |-2.29e-01
2018-01-03 | 1.6243 | looooooong |-0.80301836909080672 | 6.67e-01
2018-01-04 | 0.4356 | text |-1.957887025379132 |-1.37e+00
我还将它与tablefmt='plain'
关键字参数一起使用,以获得空间分隔值(ssv)文件的固定宽度格式,以便在文本编辑器中轻松查看
同样值得注意的是,在许多方面,它不像以前那么容易使用或定制
astropy.io.ascii.write(astropy.io.ascii.read(df.to_csv(),format='csv',header_start=0),format='fixed_width',formats={'C':'0.2e','B':'0.4f'}
|日期| B | D | A | C|
|2018-01-01 | 0.8080 |这里是| 1.54302012213 | 8.81e-01|
|2018-01-02 |-1.0354 | some |-1.0642628831 |-2.29e-01|
|2018-01-03 | 1.6243 | looooooong |-0.803018369098 | 6.67e-01|
|2018-01-04 | 0.4356 |文本|-1.95788702538 |-1.37e+00|
看看这个[(post)你说得对,prettytable
模型就是我要找的。对于任何需要将它保存到文件中的人,这将解决它:string=t.get\u string(border=True)text\u file.write(string)
。当然,您必须打开和关闭文件。谢谢!这确实有帮助,但后来我意识到prettytable
更适合我的要求。但我非常感谢这一技巧,再次感谢。
from prettytable import PrettyTable
# Initialize the object passing the table headers
t = PrettyTable(['A', 'B', 'C'])
t.align='l'
t.border=False
t.add_row([111,222,333])
t.add_row([444,555,666])
t.add_row(['longer text',777,'even longer text here'])
print str(t)
A B C
111 222 333
444 555 666
longer text 777 even longer text here