我正在努力处理我导入的2个csv文件
csv文件如下所示:
csv1
planet,diameter,discovered,color
sceptri,33.41685587,28-11-1611 05:15, black
...
csv2
planet,diameter,discovered,color
sceptri,33.41685587,28-11-1611 05:15, blue
...
在两个csv文件中,存在相同的行星,但顺序不同,有时具有不同的值(不匹配)
每个行星的数据(直径、发现和颜色)都是独立输入的。我想交叉检查这两张表,找出所有不匹配的字段。然后我想生成一个新文件,每个错误包含一行错误描述
例如: 权杖:不匹配(黑色/蓝色)
这是到目前为止我的代码
with open('planets1.csv') as csvfile:
a = csv.reader(csvfile, delimiter=',')
data_a= list(a)
for row in a:
print(row)
with open('planets2.csv') as csvfile:
b = csv.reader(csvfile, delimiter=',')
data_b= list(b)
for row in b:
print(row)
print(data_a)
print(data_b)
c= [data_a]
d= [data_b]```
thank you in advance for your help!
通过对csv文件中的行进行排序,然后比较相应的行以查看是否存在差异,可以解决此类问题
此方法使用函数样式执行比较,并将比较任意数量的csv文件
它假定CSV包含相同数量的记录,并且列的顺序相同
假设两个文件中的行星名称都正确,下面是我的建议
列表
new_file
可以另存为新文件,请参见Writing a list to file我建议用熊猫来完成这样的任务
首先,您需要将csv内容读入dataframe对象。这可以通过以下方式完成:
如果CSV文件中没有每列的名称,则可能需要为每列声明名称
为了代码的可复制性,我将在下面定义没有csv的dataframe对象:
请注意,df1如下所示:
df2看起来是这样的:
以下代码比较数据帧,将比较连接到新数据帧,然后将结果保存到CSV:
最终结果如下所示:
希望这有帮助
相关问题 更多 >
编程相关推荐