Pandas库对比筛选多个txt文件:相同数据和不同数据

假设有两个txt文件,分别为'file1.txt'和'file2.txt',内容如下:

file1.txt:

id,name,age
1,John,25
2,Kate,30
3,David,20

file2.txt:

id,name,age
1,John,25
3,David,22
4,Lisa,28

我们可以使用pandas库来读取这两个文件,对比筛选出两个文件中相同的数据和不同的数据。

步骤:

  1. 导入pandas库:
import pandas as pd
  1. 使用read_csv()函数读取txt文件:
df1 = pd.read_csv('file1.txt')
df2 = pd.read_csv('file2.txt')
  1. 使用merge()函数对比相同的数据:
# 对比相同的数据
df_same = pd.merge(df1, df2, on=['id', 'name', 'age'])
print('相同的数据:')
print(df_same)
  1. 使用concat()和drop_duplicates()函数对比不同的数据:
# 对比不同的数据
df_diff = pd.concat([df1, df2]).drop_duplicates(keep=False)
print('不同的数据:')
print(df_diff)

运行结果:

相同的数据:
   id   name  age
0   1   John   25
1   3  David   20
不同的数据:
   id  name  age
1   2  Kate   30
2   3  David   22
3   4  Lisa   28

可以看到,相同的数据是id为1和3的数据,不同的数据是id为2、3、4的数据。

通过以上代码,我们可以使用pandas库轻松地对比筛选多个txt文件中的数据,并提取出相同和不同的数据。

Pandas库对比筛选多个txt文件:相同数据和不同数据

原文地址: https://www.cveoy.top/t/topic/jEuk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录