python 2.7 input csv file
person alpha beta gamma
alex 1 2
bob 2 1
zac 1 2
output format
Person data qty<2
alex beta,gamma beta
bob alpha,gamma gamma
zac alpha,beta alpha
The following should work for you given the following input (tab-delimited):
person alpha beta gamma
alex 1 2
bob 2 1
zac 1 2
Code:
#!python2
import csv
import os
# open in binary mode per Python 2 csv docs
with open('x.csv','rb') as fin:
csv_reader = csv.reader(fin,delimiter='\t')
headers = next(csv_reader)
item_names = headers[1:] # collect names of data columns
with open('y.csv','wb') as fout:
csv_writer = csv.writer(fout,delimiter='\t')
csv_writer.writerow(['Person','data','qty<2'])
for row in csv_reader:
person = row[0]
items = row[1:] # list of the alpha/beta/gamma data
data = [] # collect the names of non-empty data
qtylt2 = [] # collect the names of <2 data
for i,item in enumerate(items):
if item:
data.append(item_names[i])
if int(item) < 2:
qtylt2.append(item_names[i])
csv_writer.writerow([person,','.join(data),','.join(qtylt2)])
Output:
Person data qty<2
alex beta,gamma beta
bob alpha,gamma gamma
zac alpha,beta alpha
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.