PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

[FIXED] How to provide column titles in Python

 August 29, 2022     csv, numpy, python     No comments   

Issue

I am saving arrays A, B, C, D in four separate columns in a CSV file. However, I don't know how to add column titles. The current and desired outputs are attached.

import numpy as np
import csv 

A=np.array([[1,2,3],[4,5,6],[7,8,9]])
B=np.array([[11,12,13],[14,15,16],[17,18,19]])
C=np.array([[21,22,23],[24,25,26],[27,28,29]])
D=np.array([[31,32,33],[34,35,36],[37,38,39]])

with open('Data.csv', 'w') as f:
        print(A)      
        print(B)  #for pressure
        print(C)  #for velocity
        print(D)
        writer = csv.writer(f)
        writer.writerows(zip([A],[B],[C],[D]))

The current output is

enter image description here

The desired output is

enter image description here


Solution

you can add an additional writerow() to add the header row. Also, you need add newline='' in the open statement, so that an additional newline is not added. Updated code below...

import numpy as np
import csv 

A=np.array([[1,2,3],[4,5,6],[7,8,9]])
B=np.array([[11,12,13],[14,15,16],[17,18,19]])
C=np.array([[21,22,23],[24,25,26],[27,28,29]])
D=np.array([[31,32,33],[34,35,36],[37,38,39]])

with open('Data.csv', 'w', newline='') as f:
        print(A)      
        print(B)  #for pressure
        print(C)  #for velocity
        print(D)
        writer = csv.writer(f)
        myheaders = list('ABCD')
        writer.writerow(myheaders)
        writer.writerows(zip([A],[B],[C],[D]))

Output

enter image description here



Answered By - Redox
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing