作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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/
使用登录后,我想吐出用户名。 但是,当我尝试单击登录按钮时, 它给了我力量。 我看着logcat,但是什么也没显示。 这种编码是在说。 它将根据我在登录屏幕中输入的名称来烘烤用户名。 不会有任何密码。
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
我是一名优秀的程序员,十分优秀!