python - 我们可以在 pandas 的 iloc 中使用 contains 属性吗?

标签 python pandas

问题:我必须在系列集中循环以找出系列值是否包含子集字符串“Hi”?

说明:这里有两个数据帧 Dataframe1 和 Dataframe2,我试图查找 Dataframe2 的“源代码”是否包含 Dataframe1 的字符串并将结果设置在 Dataframe3 中。

import pandas as pd
import numpy as np
import openpyxl

data = {'Fields' : ['Hi', 'How', 'Are', 'You']}

Dataframe1 = pd.DataFrame(data)

data2 = {'SourceCode' : ['LMNOHiPQR', 'LMNOHowPQR']}

Dataframe2 = pd.DataFrame(data2)

data3 = {'dummy' : []}

Dataframe3 = pd.DataFrame(data3)

for i in range(0,len(Dataframe1)):      
    current_string=Dataframe1['Fields'][i]
    for j in range(0,len(Dataframe2)): 
            if Dataframe2['SourceCode'].iloc[j].contains(current_field):
                Dataframe3['dummy'].iloc[j] =Dataframe2['SourceCode'].iloc[j]

期望:我期望包含 Dataframe1 中的字符串的“SourceCode”值在 Dataframe3 中设置。但我收到以下错误。

RESULT: 
if Dataframe2['SourceCode'].iloc[j].contains(current_field):

AttributeError: 'str' object has no attribute 'contains'

伙计们,作为上一个问题的补充,我现在想在 Dataframe3 中添加一个带有相应字符串(即 current_field)的单独列。因此我会知道观察对应于哪个字符串。请帮我解决这个问题。

最佳答案

IIUC 你应该使用 in 运算符来测试字符串中是否存在子字符串,因此循环应该类似于:

for i in range(0,len(Dataframe1)):      
    current_string=Dataframe1['Fields'][i]
    for j in range(0,len(Dataframe2)): 
        if current_string in Dataframe2['SourceCode'].iloc[j]:
                Dataframe3.loc[j, 'dummy'] = Dataframe2['SourceCode'].iloc[j]

但是,不建议使用 pandas.DataFrames 进行循环。因此,替代解决方案可能是使用 Series.str.contains方法和boolean indexing :

Dataframe3 = Dataframe2[Dataframe2.SourceCode.str.contains('|'.join(Dataframe1.Fields))]

[输出]

                                   SourceCode
0   try{string s = "Hi"}catch { }return null;
1  try{string s = "How"}catch { }return null;

如果您需要匹配包含单词边界,请首先创建正则表达式模式,例如:

pat = r'\b' + r'\b|\b'.join(Dataframe1.Fields) + r'\b'
Dataframe3 = Dataframe2[Dataframe2.SourceCode.str.contains(pat)]

关于python - 我们可以在 pandas 的 iloc 中使用 contains 属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56073079/

相关文章:

Python - 过滤字典 JSON 响应以仅发回两个值或转换为字符串?

python - 如何返回值 If One List Against Another Dataframe (Pandas)?

python - 通过字符串变量 reshape 数据框

python - 用 Pandas 折叠重复的行

python - python 中的条件替换和嵌套 for 循环

python - 当在每一行中需要使用整个数据进行比较时,在 Pandas 中使用矢量化

python - 将数组中的数组与两个数字相乘

python - 按顺序查找字段

python - 请求 : Return file object from url (as with open ('' ,'rb' ) )

python - 比较同一 pandas 数据帧中 2 列的值并基于比较返回第三列的值