如何使用Python连接CSV行

时间:2014-04-09 21:45:46

标签: python csv concatenation

假设我有一个CSV文件,如下所示:

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

我希望能够连接列行,以便我有以下列表:

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

我不包括列标题。 我怎么能这样做?

编辑:我已将CSV文件加载到程序中。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

只需阅读所有行,然后将它们“加入”

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

答案 2 :(得分:0)

import pandas as pd
df = pd.read_csv('filename.csv')
answer = [''.join(df.values[:,i]) for i in range(len(df.columns))]

如果你经常进行这种数据处理,那么大熊猫会改变你的生活。