gpt4 book ai didi

python - 如何验证两个不同的 .csv 文件列 id 是否与 python 匹配?

转载 作者:太空宇宙 更新时间:2023-11-04 10:27:05 25 4
gpt4 key购买 nike

我有两个不同的 .csv 文件,但它们具有相同的 id 列。

file_1.csv:
id, column1, column2
4543DFGD_werwe_23, string
4546476FGH34_wee_24, string
....
45sd234_w32rwe_2342342, string

另一个:

file_1.csv:
id, column3, column4
4543DFGD_werwe_23, bla bla bla
4546476FGH34_wee_24, bla bla bla
....
45sd234_w32rwe_2342342, bla bla bla

我如何验证这两列与 csv 模块或 pandas 匹配(具有相同的 ID)或相同?

最佳答案

加载后您可以调用equals在 id 列上:

df['id'].equals(df1['id'])

这将返回 TrueFalse 如果它们完全相同,长度和相同顺序的相同值

In [3]:

df = pd.DataFrame({'id':np.arange(10)})
df1 = pd.DataFrame({'id':np.arange(10)})
df.id.equals(df1.id)
Out[3]:
True

In [7]:

df = pd.DataFrame({'id':np.arange(10)})
df1 = pd.DataFrame({'id':[0,1,1,3,4,5,6,7,8,9]})
df.id.equals(df1.id)
Out[7]:
False
In [8]:

df.id == df1.id
Out[8]:
0 True
1 True
2 False
3 True
4 True
5 True
6 True
7 True
8 True
9 True
Name: id, dtype: bool

加载 csvs:

df = pd.read_csv('file_1.csv')
df1 = pd.read_csv('file_2.csv') # I'm assuming your real other csv is not the same name as file_1.csv

然后您可以执行与上面相同的比较:

df.id.equals(df1.id)

如果您只想比较 id 列,您可以指定只加载该列:

df = pd.read_csv('file_1.csv', usecols=['id'])
df1 = pd.read_csv('file_2.csv', usecols=['id'])

关于python - 如何验证两个不同的 .csv 文件列 id 是否与 python 匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28772710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com