将多行输出打印为列值

时间:2019-05-30 12:02:18

标签: python arrays pandas sorting printing

假设

A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

print('Group  '+ A)
print('Number  '+ B)
print('Angle  '+ C)
print('Max value  ' + D)

我的实际输出是这种形式,

Group  Second
Number  Odd
Angle  Inclined
Max Value  Maximum

预期输出: 我想将这些索引安排为列标签,并将输出存储在csv文件中,如下所示:

enter image description here

像这样,如果存在'N'值,则csv文件应将所有值存储在另一个值之下

1 个答案:

答案 0 :(得分:4)

通过构造函数创建DataFrame

A='First'
B='Random'
C='Degree'
D='Largest'

c = ['Group', 'Number','Angle','Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)
   Group  Number   Angle Max value
0  First  Random  Degree   Largest

然后是DataFrame.to_csv

df.to_csv('file', index=False)

或仅使用python:

import csv
with open("out.csv","w") as f:
    wr = csv.writer(f, delimiter=',')
    wr.writerow(c)
    wr.writerow([A,B,C,D])