我对编程相当陌生,想编写这个在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)
你知道怎么解决这个问题吗?你知道吗
欢迎使用编程。让我给你介绍一下神奇的pandas library。你知道吗
在我的脑子里,有件事可以解决你的问题。(我不是说它效率高!因此,对于大型数据集,这可能是一个问题)
谢谢Wboy你的贡献,你的意见真的很有用。你知道吗
我利用熊猫图书馆找到了解决这个问题的办法。代码如下:
识别并传输“公共”列:
从数据帧df2中删除“不常见”列:
将输出另存为.csv文件:
我相信这不是一个最佳的解决方案,我希望代码可以在识别和传输“公共”列方面得到改进。我的代码中充满了if/elif语句,我确信这里一定有更好的实现方法。你知道吗
相关问题 更多 >
编程相关推荐