【发布时间】:2016-11-05 10:55:52
【问题描述】:
我对编程很陌生,想编写这个程序,在file1.csv 和file2.csv 之间传输公共列
输入:
file1.csv 看起来像这样:
ID,Nickname,Gender,SubjectPrefix,SubjectFirstName,Whatever1A,Whaterver2A,SubjectLastName
1,J.,M,Dr.,Jason,,,Allan
2,B.,M,Mr.,Brian,,,Welch
file2.csv 看起来像这样:
nickname,gender,city,id,prefix_name,first_name,Whatever1B,last_name,Whatever2B,Whatever3B,Whatever4B
问题:
如何比较file1.csv和file1.csv的表头来识别并传递它们之间的“共同”列。 “通用”列是具有相似命名约定的列(即ID 和id 、 Nickname 和nickname),或者不一定具有相同的列命名约定,但要存储相同的数据(即SubjectPrefix 和prefix_name 、 SubjectFirstName 和first_name)。
输出:
输出应该是这样的。
-
注意:转移的列
"id"、"nickname"和"gender"是file1.csv和file2.csv标题之间命名相似的列。而"prefix_name"和"first_name"列分别对应"SubjectPrefix"和"SubjectFirstName"。id,nickname,gender,prefix_name,first_name,last_name 1,J.,M,Dr.,Jason,Allan 2,B.,M,Mr.,Brian,Welch
我试过这段代码:
import csv
import collections
csv_file1 = "file1.csv"
csv_file2 = "file2.csv"
data1 = list(csv.reader(file(csv_file1,'r')))
data2 = list(csv.reader(file(csv_file2,'r')))
file1_header = data1[0][:] #get the header from file1
file2_header = data2[0][:] #get the header from file2
lowered_file1_header = [item.lower() for item in file1_header] #lowercase file1 header
lowered_file2_header = [item.lower() for item in file2_header] #lowercase file2 header anyways
col_index_dict = {}
for column in lowered_file1_header:
if column == "subjectprefix": # identify "subjectprefix" column in file1.csv
col_index_dict[column] = lowered_file1_header.index(column)
elif column == "subjectfirstname": # identify "subjectfirstname" column in file1.csv
col_index_dict[column] = lowered_file1_header.index(column)
elif column in file2_header: # identify the columns with same naming
col_index_dict[column] = lowered_file1_header.index(column)
else:
col_index_dict[column] = -1 # mark the not matching columns
# Build header
output = [col_index_dict.keys()]
is_header = True
for row in data1:
if is_header is False:
rowData = []
for column in col_index_dict:
column_index = col_index_dict[column]
if column_index != -1:
rowData.append(row[column_index])
else:
rowData.append('')
output.append(rowData)
else:
is_header = False
print(output)
知道如何解决这个问题吗?
【问题讨论】:
标签: python csv for-loop pandas dictionary