gpt4 book ai didi

python - 如何在Python中比较两个不同.csv文件中的列?

转载 作者:行者123 更新时间:2023-12-01 09:34:05 24 4
gpt4 key购买 nike

import pandas as pd
A=pd.read_csv("C:/Users/amulya/Desktop/graves lab/main_now.csv", index_col=False, header=None)
DATA1=pd.DataFrame(A)
DATA1[0]
B=pd.read_csv("C:/Users/amulya/Desktop/graves lab/words.csv", index_col=False, header=None)
DATA2=pd.DataFrame(B)
DATA2[0]
for xrow in range (1,len(DATA1)):
for yrow in range (1,len(DATA2)):
if DATA2== DATA1:
print(DATA1[3])

“在 DATA1 文件的第 1 列中,有从 1-3000 的数字,在 DATA2 文件的第 1 列中,有 465 个随机数字。我想在 DATA1 文件中搜索这些数字并打印其余的列”

最佳答案

您可以使用 isin 查找 Data2 的 col1 中的值是否是 Data1 的 col1 中的值,然后按该值对 Data1 进行切片 bool 数据帧。

import pandas as pd
df1 = pd.DataFrame({'col1': [1,2,3,4,5,6,7,8,9],
'col2': [1,3,5,7,9,11,13,15,17]})
df2 = pd.DataFrame({'col1': [1, 101, 6, 9, 4]})

我们有两个 DataFrame df1df2。您可以通过 df['col1'] 或等效的 df.col1

按列名称选择第一个数据帧的第一列
df1.col
#0 1
#1 2
#2 3
#3 4
#4 5

你想要的条件是df1.col1中的值是否出现在df2的第一列中。这是通过 isin 函数完成的。语法如您所料,它会查找“df1.col1 是否在 df2.col1 中”并返回 True/False 数据帧。

df1.col1.isin(df2.col1)
#0 True
#1 False
#2 False
#3 True
#4 False
#5 True

当您通过这个 true false 数据帧对 df1 进行切片时,它仅返回 TRUE 的行,在本例中为索引 0、3、5 和 8。它将返回所有列,因为您仅按行对数据帧进行切片。

df1[df1.col1.isin(df2.col1)]
# col1 col2
#0 1 1
#3 4 7
#5 6 11
#8 9 17

关于python - 如何在Python中比较两个不同.csv文件中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684949/

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