0

Lets say I have a CSV file which looks like:

  A B C D
1 f g h j
2 s x c d
3 c f t y
4 f u i p

I would like to be able to concatenate the column rows so that I have lists which looks like:

 fscf (column A)
 gxfu (column B)
 hcti (column C)
 jdyp (column D)

I do not which to include the column headers. How can I do this?

Edit: I have the CSV file loaded into the program already.

1
  • values=selectedColumn(i)*totalWidth Commented Apr 9, 2014 at 21:48

3 Answers 3

1
import csv
rows = csv.reader(open('foo.csv', 'rU'),delimiter=',')
#merged_col1 = merged_col2 = merged_col3 = merged_col4 = []
headers = True
'''
my foo.csv:
HEADER1,HEADER2,HEADER3,HEADER4
a,b,c,d
e,f,g,h
i,j,k,l
m,n,o,p
'''
merged_col1 = []
merged_col2 = []
merged_col3 = []
merged_col4 = []
for row in rows:
    if headers:    #skip headers
        headers = False
        continue
    merged_col1.append(row[0])
    merged_col2.append(row[1])
    merged_col3.append(row[2])
    merged_col4.append(row[3])

print ''.join(merged_col1)
print ''.join(merged_col2)
print ''.join(merged_col3)
print ''.join(merged_col4)


OUTPUT:
-------
aeim
bfjn
cgko
dhlp
Sign up to request clarification or add additional context in comments.

2 Comments

This is good, however the merge includes the headers. How do I prevent the headers from being in the merge?
@Glitchezz check out the new code, it'll skip the headers.
1
import pandas as pd
df = pd.read_csv('filename.csv')
answer = [''.join(df.values[:,i]) for i in range(len(df.columns))]

If you do this kind of data manipulation a lot, then pandas is going to change your life.

Comments

0

Just read all the rows, and "join" them together

with open("input.txt","rb") as myfile:
     reader = csv.reader(myfile,delimiter=" ")
     master_row = ["","","",""]
     for row in reader:
         master_row = [master_row[col] + row[col] for col in range(0,len(master_row))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.