gpt4 book ai didi

python - 我想在 csv 文件中搜索数据,其中数据取自 file1.csv 并使用 pandas 在 file2.csv 中搜索

转载 作者:行者123 更新时间:2023-12-01 07:23:01 25 4
gpt4 key购买 nike

我在 file1.csv 中有一个数据列表(包含超过 1000 行),使用该数据我必须在 file2.csv(包含超过 1700 行)中搜索,如果在 file1 中找到数据,则标记为 true。 csv 也是,我是 python 新手,如果有人帮助我,我将不胜感激。

文件1.csv

qwee
asdf
erttg
hrthr
rthtr
tjes
tykiut
fdh
yukyu

文件2.csv

fdh
gryj
uilyh
hrthr
yuhh
ljjj
qwee
erttg
rthtr

输出:

fdh     TRUE
gryj FALSE
uilyh FALSE
hrthr TRUE
yuhh FALSE
ljjj FALSE
qwee FALSE
erttg TRUE
rthtr TRUE



import numpy as np
import pandas as pd

filename = 'file2.csv'
df = pd.read_csv(filename)


found = df.apply(lambda row: row.astype(str).str.contains('hrthr').any(), axis=1)
print(found)

我得到以下输出:

0       False
1 True
2 False
3 False
4 False
...
1754 False
1755 False
1756 False
1757 False
1758 False
Length: 1759, dtype: bool

最佳答案

一个非常简单的方法就是检查 df1 中的 col 值是否存在于 df2 的值中:

重新创建数据集

df1 = pd.DataFrame([
['qwee'],['asdf'],['erttg'],['hrthr'],
['rthtr'],['tjes'],['tykiut'],['fdh'],
['yukyu']], columns=['col1']
)

df2 = pd.DataFrame([
['fdh'],['gryj'],['uilyh'],['hrthr'],
['yuhh'],['ljjj'],['qwee'],['erttg'],
['rthtr']], columns=['col2']
)

解决方案

df1['check'] = df1.col1.isin(df2.col2)

Out[1]:
col1 check
0 qwee True
1 asdf False
2 erttg True
3 hrthr True
4 rthtr True
5 tjes False
6 tykiut False
7 fdh True
8 yukyu False

已添加:鉴于您有相当多的行,性能不是问题:

%timeit df1['check'] = df1.col1.isin(df2.col2)

# 183 µs ± 1.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

关于python - 我想在 csv 文件中搜索数据,其中数据取自 file1.csv 并使用 pandas 在 file2.csv 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57596158/

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