pythonpandas读取csv和另外一个csv进行比较,比较两个csv文件并使用python获得区别

I have two csv files,

a1.csv

city,state,link

Aguila,Arizona,https://www.glendaleaz.com/planning/documents/AppendixAZONING.pdf

AkChin,Arizona,http://www.maricopa-az.gov/zoningcode/wp-content/uploads/2014/05/Zoning-Code-Rewrite-Public-Review-Draft-3-Tracked-Edits-lowres1.pdf

Aguila,Arizona,http://www.co.apache.az.us/planning-and-zoning-division/zoning-ordinances/

a2.csv

city,state,link

Aguila,Arizona,http://www.co.apache.az.us

I want to get the difference of result,

Here is the code which i tried,

import pandas as pd

a = pd.read_csv('a1.csv')

b = pd.read_csv('a2.csv')

mask = a.isin(b.to_dict(orient='list'))

# Reverse the mask and remove null rows.

# Upside is that index of original rows that

# are now gone are preserved (see result).

c = a[~mask].dropna()

print c

Expected Output:

city,state,link

Aguila,Arizona,https://www.glendaleaz.com/planning/documents/AppendixAZONING.pdf

AkChin,Arizona,http://www.maricopa-az.gov/zoningcode/wp-content/uploads/2014/05/Zoning-Code-Rewrite-Public-Review-Draft-3-Tracked-Edits-lowres1.pdf

But am getting Error:-

Empty DataFrame

Columns: [city, state, link]

Index: []

I want to check based on first two rows, if its same then remove it off.

Thanks in Advance.

解决方案

First, concatenate the DataFrames, then drop the duplicates while still keeping the first one. Then reset the index to keep it consistent.

import pandas as pd

a = pd.read_csv('a1.csv')

b = pd.read_csv('a2.csv')

c = pd.concat([a,b], axis=0)

c.drop_duplicates(keep='first', inplace=True) # Set keep to False if you don't want any

# of the duplicates at all

c.reset_index(drop=True, inplace=True)

print(c)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值